0

function wrapValue(n) {
  var localVariable = n;
  return function() { return localVariable; };
}

var wrap1 = wrapValue(1);
var wrap2 = wrapValue(2);
console.log(wrap1());
// → 1
console.log(wrap2());
// → 2

In this example how is it allowed to access localVariable, which is local to wrapValue() function, from the global environment?
The book, included this example, stated the reason as follows: "multiple instances of the variable can be alive at the same time".
But I didn't understand.

Moaaz Bhnas
  • 1,010
  • 7
  • 18
  • 36

1 Answers1

0

Your function sets a private value (localVariable) when called and returns it immediately so you can assign it to a another variable without change the private var inside function.

Mosè Raguzzini
  • 15,399
  • 1
  • 31
  • 43