In the following code, why are both of the methods (increment and print) listed inside of return? Why can’t you just use return counter++? Also, what does it mean to return a console.log?
function create() {
var counter = 0;
return {
increment: function() {
counter++;
},
print: function() {
console.log(counter);
}
}
}
Thanks!
What this returns is more or less a Counter, if we rename the topmost function, it should make more sense.
Well what does it do? Let’s add some comments
Example usage:
Note the variable
counterinside the function is not accessible from the outside, therefore it’s readonly, an effect you can only achieve by using a closure.