closure example from Rob

by Lucille Kenney

JavaScript

// From Alain's example at https://piazza.com/class/i1nvi95aun06l7?cid=890
console.clear();

var add = function() {
    console.log("in add function");
    var counter = 0;
    return counter++;
};

var addWithClosure = (function() {
    console.log("in addWithClosure function");
    console.log(" " );
    // this variable is now accessible by the below anonymous function.
    var counter = 0;
    // this function will ultimately become the function "add()" 
    // and will have access to the variable "counter".
    return function() {
        console.log("In closure function");
        return counter++;
    };
})();

for (var i = 0; i < 5; i++) {
    console.log(add());    
}
console.log(" ");
for (var i = 0; i < 5; i++) {
    console.log(addWithClosure());    
}