Javascript Closure Example

This example shows how you can create a closure. The add function provides the closure and it returns the addToNum1 function. The add5 variable then calls the add function passing in the argument 5 . Finally calling the add5 function and passing in the argument 2 will return 7 .

var add = function(num) {
    var num1 = num; //stays at 5
    
    var addToNum1 = function(num2) {
        return num1 + num2;
    }
    return addToNum1;
};

var add5 = add(5);
add5(2); // 7
add5(3); // 8

For more Javascript learning check out my collection .