what is closure in javascript
function OuterFunction() {
var outerVariable = 100;
function InnerFunction() {
alert(outerVariable);
}
return InnerFunction;
}
var innerFunc = OuterFunction();
what is closure in javascript
function OuterFunction() {
var outerVariable = 100;
function InnerFunction() {
alert(outerVariable);
}
return InnerFunction;
}
var innerFunc = OuterFunction();
What is Closures in JavaScript
/*A closure is the combination of a function bundled together (enclosed) with references
to its surrounding state (the lexical environment). In other words, a closure gives you
access to an outer function’s scope from an inner function. In JavaScript, closures are
created every time a function is created, at function creation time.*/
function init() {
var name = 'Mozilla'; // name is a local variable created by init
function displayName() { // displayName() is the inner function, a closure
alert(name); // use variable declared in the parent function
}
displayName();
}
init();
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()); // logs 0
counter.increment();
counter.increment();
console.log(counter.value()); // logs 2
counter.decrement();
console.log(counter.value()); // logs 1
syntax of closures
/*
{ (parameters) -> return type in
body
}
*/
var numbers = [1, 2, 3, 4]
var reversed = numbers.sorted(by: {(a: Int, b: Int) -> Bool in
return a > b
})
A closure Function
var returns_a_func = function () {
var word = 'I can see inside ' function sentence(){ var word2 = 'I can also see outside. ' console.log(word + 'and ' + word2) } return sentence;
}var finalSentence = returns_a_func()finalSentence()
JavaScript - Closures
function makeAdder(x) {
return function(y) {
return x + y;
};
}
var add5 = makeAdder(5);
var add10 = makeAdder(10);
console.log(add5(2)); // 7
console.log(add10(2)); // 12
//=====
//add5 and add10 are both closures.
//They share the same function body definition, but store different lexical environments.
//In add5's lexical environment, x is 5, while in the lexical environment for add10, x is 10.
Copyright © 2021 Codeinu
Forgot your account's password or having trouble logging into your Account? Don't worry, we'll help you to get back your account. Enter your email address and we'll send you a recovery link to reset your password. If you are experiencing problems resetting your password contact us