A closure gives you access to an outer function’s scope from an inner function//examplefunctioninit(){var name ='Mozilla';// name is a local variable created by initfunctiondisplayName(){// displayName() is the inner function, a closurealert(name);// use variable declared in the parent function}displayName();}init();
// Closures// In JavaScript, closure is one of the widely discussed and important concepts.// A closure is a function that has access to the variable from another function’s scope which is accomplished by creating a function inside a function. As defined on MDN:// “Closures are functions that refer to independent (free) variables. In other words, the function defined in the closure ‘remembers’ the environment in which it was created.”// In JavaScript, closures are created every time a function is created, at function creation time. Most JavaScript developers use closure consciously or unconsciously — but knowing closure provides better control over the code when using them.// Example:functionSpellname(name){var greet ="Hi, "+ name +"!";varsName=function(){var welc = greet +" Good Morning!";console.log(greet);};return sName;}varMyname=SpellName("Nishi");Myname();// Hi, Nishi. Good Morning!// In the above example, the function sName() is closure; it has its own local scope (with variable welc) and also has access to the outer function’s scope. After the execution of Spellname(), the scope will not be destroyed and the function sName() will still have access to it.
-->closure in javascript
//closure is the combination of function and the lexical enviornment in//which the function is defined.closure give you access to the functions//and variables outside the function.functionouter(){const outerData ="outer";functioninner(){const innerData="inner";console.log(`${outerData} and{innerData}`);}inner();}outer();
// A closure is a function having access to the parent scope, // even after the parent function has popped.functiongreeting(){let message ='Hi';functionsayHi(){console.log(message);}return sayHi;}let hi =greeting();hi();// still can access the message variable
functionfoo(){const secret =Math.trunc(Math.random()*100)returnfunctioninner(){console.log(`The secret number is ${secret}.`)}}const f =foo()// `secret` is not directly accessible from outside `foo`f()// The only way to retrieve `secret`, is to invoke `f`Run code snippet
functionmakeAdder(x){returnfunction(y){return x + y;};}var add5 =makeAdder(5);var add10 =makeAdder(10);console.log(add5(2));// 7console.log(add10(2));// 12//my words: what this code do is basically a nested function that will return//its inner function (un-activated). So var add5 in line 7 activated the outer//function with 5 as parameter which makes add5 is now the nameless function at//line 2 that will return 5 + y;//MDN words://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.
functionmakeAdder(x){returnfunction(y){return x + y;};}var add5 =makeAdder(5);var add10 =makeAdder(10);console.log(add5(2));// 7console.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.
// global scopevar e =10;functionsum(a){returnfunction(b){returnfunction(c){// outer functions scopereturnfunction(d){// local scopereturn a + b + c + d + e;}}}}console.log(sum(1)(2)(3)(4));// log 20// You can also write without anonymous functions:// global scopevar e =10;functionsum(a){returnfunctionsum2(b){returnfunctionsum3(c){// outer functions scopereturnfunctionsum4(d){// local scopereturn a + b + c + d + e;}}}}var sum2 =sum(1);var sum3 =sum2(2);var sum4 =sum3(3);var result =sum4(4);console.log(result)//log 20
functionCounter(){var counter =0;alert("XXXXX");functionincreaseCounter(){return counter +=1;}return increaseCounter;}/***/
const counter = new Counter();
console.log(counter());
console.log(counter());
/*note that alert("XXXX") only executes once*//*think of counter() = new Counter() declaration as storing the value of ONE Counter function execution and
the remaining times you use counter(), you reexecute only the returned function*//*use counter() instead of Counter() if you want alert("XXXX") to execute only once AND for you to be able to return an actual value otherwise you only console.log a function and alert executes multiple times*/
// A Closure gives you access to an outer function's scope from an inner function.// ExamplefunctionmyNameIs(name){returnfunction(){console.log('Hi my name is '+ name);}}let maxine =myNameIs('Maxine');let amber =myNameIs('Amber');maxine();amber();
functionnumberGenerator(){// Local “free” variable that ends up within the closurevar num =1;functioncheckNumber(){console.log(num);}
num++;return checkNumber;}var number =numberGenerator();number();// 2
/*
A lexical environment is part of every execution context (stack frame) and is a map between identifiers (i.e. local variable names) and values.
Every function in JavaScript maintains a reference to its outer lexical environment. This reference is used to configure the execution context created when a function is invoked.
This reference enables code inside the function to "see" variables declared outside the function, regardless of when and where the function is called.
If a function was called by a function, which in turn was called by another function, then a chain of references to outer lexical environments is created.
This chain is called the scope chain.
In the following code, inner forms a closure with the lexical environment of the execution context created when foo is invoked, closing over variable secret:
*/functionfoo(){const secret =Math.trunc(Math.random()*100)returnfunctioninner(){console.log(`The secret number is ${secret}.`)}}const f =foo()// `secret` is not directly accessible from outside `foo`f()// The only way to retrieve `secret`, is to invoke `f`Run code snippet
//ClosuresClosures means a function bind together with its lexical environment
ORYou can say a function along with its lexical scope bundle together forms
a closure
ORIn other words, a closure gives you access to an outer function's
scope from an inner function.//Examplefunctionx(){var a =7;functiony(){//function y bind with its lexical enviromentconsole.log(a);}
a =100;return y;}var z =x();console.log(z)//Output is 100
// javascript closure example// outer functionfunctiongreet(){// variable defined outside the inner functionlet name ='John';// inner functionfunctiondisplayName(){// accessing name variablereturn'Hi'+' '+ name;}return displayName;}const g1 =greet();console.log(g1);// returns the function definitionconsole.log(g1());// returns the value
varreturns_a_func=function(){var word ='I can see inside 'functionsentence(){var word2 ='I can also see outside. 'console.log(word +'and '+ word2)}return sentence;}var finalSentence =returns_a_func()finalSentence()
//Closures are the inner functions that are embedded in parent functionfunctiongetName(){// print name function is the closure since it is child function of getNamefunctionprintName(){return'Kevin'}// return our function definitionreturn printName;}const checkNames =getName();console.log(checkNames());
functioncreateObject(){let x =42;return{log(){console.log(x)},increment(){ x++},update(value){ x = value }}}const o =createObject()
o.increment()
o.log()// 43
o.update(5)
o.log()// 5const p =createObject()
p.log()// 42
/*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.*/functioninit(){var name ='Mozilla';// name is a local variable created by initfunctiondisplayName(){// displayName() is the inner function, a closurealert(name);// use variable declared in the parent function}displayName();}init();