Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

144
Views
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"

about 4 years ago ยท Santiago Gelvez
2 answers
Answer question

0

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
  }
}
about 4 years ago ยท Santiago Gelvez Report

0

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 ๐Ÿ‘๐Ÿป

about 4 years ago ยท Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
ยฉ 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!