Search code examples
javascriptclosuresnested-function

Calling a nested function JavaScript


I am new to JavaScript. I have this piece of code. I need to print the following:

//counter() should return the next number.
//counter.set(value) should set the counter to value.
//counter.decrease() should decrease the counter by 1

function makeCounter() {
  let count = 0;

  function counter() {
    return count++;
  }

  counter.decrease = function () {
    return count--;
  };

  counter.set = function (value) {
    return count = value;
  };
}

How can I call the 3 nested functions outside?


Solution

  • You just have to return your counter.

    function makeCounter() {
      let count = 0;
    
      function counter() {
        return count++;
      }
    
      counter.decrease = function () {
        return count--;
      };
    
      counter.set = function (value) {
        return count = value;
      };
      
      return counter;
    }
    
    const myCounter = makeCounter();
    
    console.log(myCounter()); // 0
    console.log(myCounter()); // 1
    console.log(myCounter.set(42)); // 42
    console.log(myCounter()); // 42 (*see why next)
    console.log(myCounter.decrease()); // 43 (*see why next)
    console.log(myCounter()); // 42

    • Be carefull with notation count++ because it returns count then add 1. If you want to add 1 then return the new value of count, please write ++count.