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?