0

Can anyone explain how this code works?

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

Reference: https://mozilla.org/en/docs/Web/JavaScript/Closures

Hitesh Misro
  • 3,397
  • 1
  • 21
  • 50
  • Just a pointer, its called Currying function – Rajesh Mar 15 '17 at 06:48
  • 1
    This might help: https://medium.com/@kbrainwave/currying-in-javascript-ce6da2d324fe#.gkany5rxq – Rajesh Mar 15 '17 at 06:50
  • One of the most important and ticklish features with closures is that the inner function still has access to the outer function’s variables even after the outer function has returned. When functions in JavaScript execute, they use the same scope chain that was in effect when they were created. This means that even after the outer function has returned, the inner function still has access to the outer function’s variables. – Hanif Mar 15 '17 at 06:56

3 Answers3

1

When you call your makeAdder(5), it returns the reference to a new function.

function(y) {
    return x + y;
};

So add5 keeps the reference. After it when you call add5(2), you pass the 2 to the function. In it when it wants to return x + y, it starts to find the variables. Starting from x, it looks and see's that the x is not defined in it and goes to the scope in which inner function was defined ` here

function makeAdder(x) {
  return function(y) {
    return x + y;
  };
}

It see's than x was defined here, because you call and pass x during var add5 = makeAdder(5);. After it goes to find y and finds in it's scope. And after all returns x + y.

The idea is this, every function has a reference to it's creater (where it was defined) and when it doesn't find a variable, it goes to find in it's greater and so till to global scope.

Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
1
function makeAdder(x) {
  return function(y) {
    return x + y;
  };
}

When you do var add5 = makeAdder(5); the add5 becomes a function which was returnd my makeAdder, the add5 will be following

function(y){
   return 5 + y;
}

so when you do add5(2) it will do 5 + 2 and will return 7;

Akshay
  • 3,558
  • 4
  • 43
  • 77
0
makeAdder(5) 

x => 5 and y is not having value so x+y => 5+0 => 5

var add5 = makeAdder(5);
add5(2);

we have created variable for the function makeadder with x => 5 so now we pass y => 2 and x => 5 so x+y => 5+2 => 7

This property of outer function variable accessible in inner function is called closure property in javascript. Also adding to that y variable is not accessible to outer function.

Macfer Ann
  • 153
  • 1
  • 9