Home > Blockchain >  Return a function that when invoked increments and returns a counter variable
Return a function that when invoked increments and returns a counter variable

Time:10-28

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!

CodePudding user response:

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))
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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);
}
}

CodePudding user response:

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));
  • Related