Here are two ways of writing a function that includes an IIFE:
function f() {
let count=0;
return function() {
return ++count;
}
}
const g = (function() {
let count=0;
return function() {
return ++count;
}
})();
f() returns function () { return ++count; }
When g() is run several times, it returns 1, 2, 3... which is the intention.
Now another example:
function f() {
return "This is f()";
}
const g = (function() {
return "This is g()";
})();
In this case f() returns "This is f()" and g() is a script error.
I've done a lot of coding in C-ish languages, but am new to JavaScript. What am I missing?
In response to the first answer, here is an executable code snippet. If function f(){...}
were the same as const f = (function () {...})()
I would expect both to run. They do not.
function f() {
return "This is f()!";
}
console.log(f());
const h = f;
console.log(h());
const g = (function() {
return "This is g()";
})();
console.log(g());