closure in js 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: what is closure in javascript
function OuterFunction() {
var outerVariable = 100;
function InnerFunction() {
alert(outerVariable);
}
return InnerFunction;
}
var innerFunc = OuterFunction();
Example 3: 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 4: javascript closure
function init() {
var name = 'Mozilla';
function displayName() {
alert(name);
}
displayName();
}
init();
Example 5: closures in javascript
function OuterFunction() {
var outerVariable = 100;
function InnerFunction() {
alert(outerVariable);
}
return InnerFunction;
}
var innerFunc = OuterFunction();
innerFunc();
Example 6: closure in javascript
function makeFunc() {
var name = 'Mozilla';
function displayName() {
alert(name);
}
return displayName;
}
var myFunc = makeFunc();
myFunc();