0

recently , I'm learning coding , and here's the code of teaching closure

function accumulator(){
    let sum =0;
    return (num) =>{
        sum = sum + num;
        return sum;
    }
}

const acc = accumulator();

acc(3)
acc(5)

result :3 & 8

Now , I've a question , why the parameter of acc(3) which is equal to accumulator(3) can be passed down to inner function parameter num , (num)=> , without any variable declared? any concept involved in closure?

Andy
  • 11
  • 1
  • The syntax `(num) =>` **is** declaring the variable (as a function parameter) – Quentin Jun 06 '23 at 19:32
  • the variable declared in inner function can takes the values in outer function acc() ? – Andy Jun 06 '23 at 19:37
  • Slight nitpick... *"which is equal to accumulator(3)"* - No it isn't. It's equal to `accumulator()(3)`, with the additional critical difference that `accumulator()(3)` doesn't retain a reference to the result of `accumulator()` to be used later for further "accumulation". – David Jun 06 '23 at 19:39
  • @Andy — `acc` isn't the outer function. The outer function is `accumulator`. When you call it it returns the inner function which is assigned to `acc`. – Quentin Jun 06 '23 at 19:42
  • `acc` is just a variable name. Its value is the object **returned** by `accumulator()`. For example if you declare `function accumulator() {return 'Hello'}` then the value of `acc` would be the string `"Hello"`. Your `accumulator()` function returns a function - the function `(num) => {...}`. `num` is **NOT** being passed through to the inner function. `acc` **IS** the inner function. What's being passed through is `sum` - through a closure. – slebetman Jun 06 '23 at 21:26

0 Answers0