Skip to content
Advertisement

calling a function outside of the function call in which it was defined

I am trying to log myNewFunction(),and the results shows undefined.

function outer() {
  let counter = 0;

  function incrementCounter() {
    counter++
  }
  return incrementCounter;
}

const myNewFunction = outer();

console.log(myNewFunction())
console.log(myNewFunction())
console.log(myNewFunction())

Advertisement

Answer

I am trying to log myNewFunction(),and the results shows undefined.

Because myNewFunction, which is the same as incrementCounter doesn’t return anything:

  function incrementCounter() {
    counter++
    // no return statement here
  }

If there is no explicit return statement, a function returns undefined. If you want it to return the new value of counter then do that.

function outer() {
  let counter = 0;

  function incrementCounter() {
    counter++;
    return counter;
  }
  return incrementCounter;
}

const myNewFunction = outer();

console.log(myNewFunction())
console.log(myNewFunction())
console.log(myNewFunction())
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement