0

I am reading eloquentjavascript to learn javascript but this closure thing is confusing me. warp1 is not function but it looks like function and it looks like taking argument too. How do closure functions work ? and what are the reasons we can use it ?

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
baao
  • 71,625
  • 17
  • 143
  • 203

1 Answers1

0

The outer function (wrapValue) returns a function. So the returned function gets assigned to your variables wrap1 and wrap2. That's why you can call the returned function from your variable.

Maybe it's easier to understand when we look at the following.

You can create a function like you did:

function foo() { return "foo"; }

Or you can assign a function to a variable:

var foo = function() { return "foo"; }

The second example basically does exactly the same as your closure does - it assigns a function to a variable.

In all cases, you can call the function with

foo();

Either by variable, or function name.

baao
  • 71,625
  • 17
  • 143
  • 203