Learning about closures, I wrote a function that returns a function which prints out a name to the console:
let myName = 'steven';
function printName() {
console.log(`OUTER: ${myName}`);
return function printAgain() {
console.log(`INNER: ${myName}`);
};
}
printName(); //Only prints 'OUTER: steven'
const newFunc = printName();
newFunc(); //Prints 'OUTER: steven'
//AND 'INNER: steven'
Why does the inner function only get called when I have used a function expression? Why does the function declaration only run the outer console log when i call it with printName() and not the second one?
On a similar note, if I call my function expression newFunc without the paranthesis, it only prints OUTER: steven.
However, if I use the parenthesis and call it newFunc(), it prints both OUTER: steven AND INNER: steven. Why is that?
It seems you are misunderstanding things here. In your example:
the "outer" function,
printName, logs the"OUTER"string whenever it is executed. This execution also happens to return a new function, the "inner" one. This logs the"INNER"string when executed.So, stepping through the rest of your original code:
This executes the outer function, and therefore logs the output you note. It also returns a new function, but as you don't assign this to a variable or otherwise do anything with it, we don't observe that. Note that if you were to execute this returned function, as
printName()()for example, you would see the"OUTER"printed, followed by the"INNER".Which is exactly what you then do, albeit in two stages:
You have this correct in total effect, but not on what each line is doing. The
"OUTER"output comes fromconst newFunc = printName(), which executesprintName. ThenewFunc()then calls the function returned - the inner function - and therefore logs the"INNER"output.None of this has anything to do with whether you use function declarations or function expressions, in this case.