Home > Back-end >  How to reuse a closure function assigning it to a variable or constant in JavaScript
How to reuse a closure function assigning it to a variable or constant in JavaScript

Time:06-15

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"

CodePudding user response:

const addNumbers = (a) => (b) => a   b

It's called currying, more details here.

P.S. If you want to use function syntax, it will look like this:

function addNumbers(a) {
  return function (b) {
    return a   b
  }
}

CodePudding user response:

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!            
  • Related