Josh Caffery
Josh Caffery

Reputation: 33

where does the actual parameter go in the closure function?

I am doing my 1.1 learning ( means very basic ) on Javascript, now i am stuck in the chapter of "the closure function", here are my codes..

function a() {
  let n = 0;

  function b(m) {
    n = m + n;
    return n
  }
  return b
}

let c = a();
console.log(c(3)); // result: 3
console.log(c(3)); // result: 6
console.log(c(3)); // result: 9
console.log(c(3)); // result: 12

so, I know when i give an actual parameter 3 to c, that at same time means give the actual parameter 3 to function a, like a(3), but how it goes automatically to add itself to formal parameter of function b to add itself again and again and end up being 6,9,12......etc. ? in other word, I didn't set any formal parameter in function a to catch the given actual parameter, how did all these happen ?

thanks a lot !

Upvotes: 1

Views: 70

Answers (3)

Nick Parsons
Nick Parsons

Reputation: 50874

I know when i give an actual parameter 3 to c, that at same time means give the actual parameter 3 to function a, like a(3)

This is not the case, when you give the actual parameter 3 to c, it becomes the formal parameter of the function b. Here's why:

When you return b, you're returning a function, which is yet to be called. So, you can visualize the line let c = a() as so:

let c = function b(m) {
  n = m + 0; // m + n becomes n + 0, because `n` is set to `0` initially in `a`
  return n
}

So, when you later call c(3), you're actually calling the function returned by a (ie: function b). This means, 3 becomes the formal parameter of b, which is then used as the value of m in your function.

And so, each time you perform an increment on n (by doing n = m + n), your value for n the next time you call c will be the sum of previous values passed through into c.

Upvotes: 1

Code Maniac
Code Maniac

Reputation: 37755

let c = a()

here a() returns function b() which has closure to n, now when you do c(3) you're actually passing value to b(3) and inside b you're doing n = m + n so it increases value of n by passed parameter to c() every time you call it


Watch out the debugger section of image to see what actually c has clsoures

enter image description here

function a() {
  let n = 0;

  function b(m) {
    n = m + n;
    return n
  }
  return b
}

let c = a();

console.log(c(3)); // result: 3
console.log(c(3)); // result: 6
console.log(c(3)); // result: 9
console.log(c(3)); // result: 12

Upvotes: 0

TheForgottenOne
TheForgottenOne

Reputation: 49

When you are calling c(3) it basically calls b function with parameter 3. When you are calling a() it creates a new instance of the function, and the n variable equals 0. Calling c(3) will change the value to 3, cause it updates the n value with the calculated expression (0 + 3). And so on. Calling another c(3), will update n param of your instance of function with 3 + 3. I hope it helps u understand it.

Upvotes: 0

Related Questions