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