Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this function returning a function?

Tags:

javascript

Why am I assigning counter function to count variable? And what is the purpose?

function counter() {
  var localVar = 0;
  return function() {
    localVar++;
    return localVar;
  }
}

  var count = counter(); // I am confused here.

  console.log(count());
like image 974
Md Nuhel Avatar asked Sep 10 '26 03:09

Md Nuhel


1 Answers

counter is a function-factory, it returns a function when called.

By assigning a variable to counter you can keep track of this counter and every time you call it the variable localVar will get incremented by one, if you were to always call counter()() you couldn't keep track of that value.

Example:

function counter() {
  var localVar = 0;
  return function() {
    localVar++;
    return localVar;
  }
}

var count = counter(); 

for(var i = 0; i<99; i++) count();

console.log(count()); // 100



for(var i = 0; i<99; i++) counter()();

console.log(counter()()); // 1
like image 73
Luca Kiebel Avatar answered Sep 12 '26 17:09

Luca Kiebel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!