use of closure in javascript code example
Example 1: closure in js
A closure gives you access to an outer function’s scope from an inner function
function init() {
var name = 'Mozilla';
function displayName() {
alert(name);
}
displayName();
}
init();
Example 2: javascript closure
function makeAdder(x) {
return function(y) {
return x + y;
};
}
var add5 = makeAdder(5);
var add10 = makeAdder(10);
console.log(add5(2));
console.log(add10(2));
Example 3: closures in javascript
function OuterFunction() {
var outerVariable = 100;
function InnerFunction() {
alert(outerVariable);
}
return InnerFunction;
}
var innerFunc = OuterFunction();
innerFunc();
Example 4: closure in javascript
var counter = (function() {
var privateCounter = 0;
function changeBy(val) {
privateCounter += val;
}
return {
increment: function() {
changeBy(1);
},
decrement: function() {
changeBy(-1);
},
value: function() {
return privateCounter;
}
};
})();
console.log(counter.value());
counter.increment();
counter.increment();
console.log(counter.value());
counter.decrement();
console.log(counter.value());
Example 5: closure in javascript
A closure is a function bundeled together with its lexical scope