write example of closure function in javascript
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: closures in javascript
function OuterFunction() {
var outerVariable = 100;
function InnerFunction() {
alert(outerVariable);
}
return InnerFunction;
}
var innerFunc = OuterFunction();
innerFunc();
Example 3: closure in javascript
function makeFunc() {
var name = 'Mozilla';
function displayName() {
alert(name);
}
return displayName;
}
var myFunc = makeFunc();
myFunc();