D3V
D3V

Reputation: 5

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())

Upvotes: 0

Views: 77

Answers (3)

Felix Kling
Felix Kling

Reputation: 816730

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())

Upvotes: 1

Arnas Dičkus
Arnas Dičkus

Reputation: 677

You don't need to actually call the function when passing value. If you want to get counter value. Should return it. Instead of returning incrementCounter() function in your example. I also suggest moving counter to global. To avoid counter resetting every time myNewFunction() is called.

let counter = 0;

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

const myNewFunction = outer;

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

Upvotes: 0

Siddharth Sabron
Siddharth Sabron

Reputation: 1

As what i am able to get after running your code which shws that the function which you wants to call my myNewfunction that is not defined in that block. you have to introduce it first and then use it.

{ "message": "ReferenceError: myNewFunction is not defined", "filename": "https://stacksnippets.net/js", "lineno": 21, "colno": 1 }

Upvotes: 0

Related Questions