Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading