0

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?

2
  • You cannot use counter outside if it's not exposed. Are you supposed to change this code? Or what should be done here? Commented Feb 8, 2022 at 16:18
  • I'd say you have to change this code. But I'm not sure. What is the guidance given to you for the task? You can either remove makeCounter or you can return counter from inside. Yet it might be neither. Hence my questions to you - are you supposed to change the code? Or what should be done here? Commented Feb 8, 2022 at 16:27

1 Answer 1

2

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.
Sign up to request clarification or add additional context in comments.

1 Comment

Thanq. This is exactly what I needed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.