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

142
Views
Return a function that when invoked increments and returns a counter variable

Need help, I'm stuck! I'm given

function counter(){}

and I read up on some materials and managed to come up with this

function counter(){
var currentValue = 0;

var increment = function(val){

currentValue += val;
console.log(currentValue);
}

its not working and I don't really 100% understand closures yet. Would like to know what is needed in the code and how it worked. Thank you!

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

The basic idea is that you create an inner function that captures the local variable and then return that function to the caller, who will call it:

function counter(){
  var currentValue = 0;

  return function(val){
    currentValue += val;
    return currentValue;
  }  
}

// create a counter and increment by one
let c = counter()
console.log(c(1))
console.log(c(1))
console.log(c(1))

// create a new counter and increment it by 2
let e = counter()
console.log(e(2))
console.log(e(2))
console.log(e(2))

about 4 years ago · Juan Pablo Isaza Report

0

it looks like every time you run the function, you are updating the currentValue variable to 0. A simple solve would be to define the currentValue variable as a global variable like this:

var currentValue = 0;
function counter(val) {   //where val is a number and the number you want your counter to change by
    currentValue += val;
console.log(currentValue);
}
}
about 4 years ago · Juan Pablo Isaza Report

0

Maybe this code is needed

function counter(){
  var currentValue = 0;

  return function(val){
    currentValue += val;
    return currentValue;
  }
}

var c = counter();
console.log(c(10));
console.log(c(20));
about 4 years ago · Juan Pablo Isaza 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!