Closures are scope-bounded bindings.
- hide variables
- hide private functions
- factories
function counterFactory() { | |
var counter = 0; | |
return function () { | |
return counter += 1; | |
} | |
} | |
// counter is hidden within the closure | |
console.log('counter: ', counter); // ReferenceError: counter is not defined. | |
// we can use closure for creating function factories | |
const count = counterFactory(); | |
console.log('count: ', count()); // 1 | |
console.log('count: ', count()); // 2 | |
console.log('count: ', count()); // 3 | |
console.log('count: ', count()); // 4 |