0
function add (x) {
  return function (y) {
    return x + y;
    };
  }
var add5 = add(5);
var no8 = add5(3);
alert(no8); // Returns 8

Can someone please explain me what happens whit y? How does first call of the function add returns 5? Does it ignore y or what?

darko
  • 3
  • 1
  • First call returns a function. Question has been asked before. Hopefully someone has a better time finding a dupe. – epascarello May 10 '16 at 21:19
  • The function `add` takes a number, `x`, and returns a *function* which accepts one argument (designated `y`) and adds it to `x`. So `var add5 = add(5)` returns a function that will add 5 to its argument. Then `var no8 = add5(3)` calls that function with the argument 3. – lurker May 10 '16 at 21:19

2 Answers2

1

It's called Closure, i.e. you can maintain a state by nesting function.

In this case, in first step, we are passing 5 to add() which then saves state (number that was passed) and returns a function which is using that number. Inner function knows that number even after first call has finished.

You can read more here.

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

Zohaib Ijaz
  • 21,926
  • 7
  • 38
  • 60
1

It's called closure. You should check out "You Don't Know JS - Scope & Closures" by Kyle Simpson, specifically chapter 5.

https://github.com/getify/You-Dont-Know-JS/blob/master/scope%20%26%20closures/ch5.md

daveashworth
  • 580
  • 5
  • 15