Search code examples
javascriptfunctionscopeclosuresreusability

How to reuse a closure function assigning it to a variable or constant in JavaScript


I'm solving an exercise that is intended to use closures. You must create a function that returns a function that will store a value and, when you reuse it, add the new value to the saved one.

const firstValue = myFunction(3);
const secondValue = firstValue(4);
// result => 7

this is the code that I'm using to practice closures:

function addNumbers(num) {
    let storage = 0
    let n = num
    function adding(n) {
        storage += n;
        return storage
    }
    return adding(n)
}

let firstAttemp = addNumbers(4)
let secondAttemp = firstAttemp(3)

console.log(firstAttemp)

this throw an error "Uncaught TypeError: firstAttemp is not a function"


Solution

  • As @skara stated in their comment, return adding(n) returns the result of calling adding instead of returning the function so that it may be called later with firstAttemp(3).

    Unfortunately though it still doesn't work because you don't actually assign the value passed to addNumber to be added later.

    function addNumbers(num) {
      let storage = 0;
      let n = num;
    
      function adding(n) {
        storage += n;
        return storage;
      }
      return adding;
    }
    
    let firstAttemp = addNumbers(4);
    let secondAttemp = firstAttemp(3);
    
    console.log(firstAttemp);
    console.log(secondAttemp); // 3! 😢

    You don't actually need to manually save the value of num to a variable as it is captured in the closure arround adding that is being returned.

    function addNumbers(num) {
      function adding(n) {
        return num + n;
        return storage;
      }
      return adding;
    }
    
    let firstAttemp = addNumbers(4);
    let secondAttemp = firstAttemp(3);
    
    console.log(secondAttemp); // 7 👍🏻