Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

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.
Source by developer.mozilla.org #
 
PREVIOUS NEXT
Tagged: #JavaScript #Closures
ADD COMMENT
Topic
Name
1+3 =