In a Udacity lesson on immediately invoked function expressions (regarding the provided code snippet) it says:
The function that is being returned closes over (i.e., captures) the hi variable. This allows myFunction to maintain a private, mutable state that cannot be accessed outside the function! What's more: because the function expressed is called immediately, the IIFE wraps up the code nicely so that we don't pollute the global scope.
I'm strugggling to understand what calling the anonymous function immediately has to do with prevent the variable hi
from "polluting the global scope," and since hi
is already defined in a function, isn't it already in local/private scope?
const myFunction = (
function () {
const hi = 'Hi!';
return function () {
console.log(hi);
}
}
)();
It doesn't.
Being a function stops it polluting the global scope.
Variables declared inside a function exist only within that function
In modern JavaScript, you have
let
and block scope (and I'm pretty sureconst
has block scope, too), so you could just do this:This creates
myFunction
without leakinghi
into the surrounding scope.In traditional JavaScript, where you only have
var
and function scope, you could do this:a_private_scope
limits the scope ofhi
, but (it being a function declaration) it needs to be called explicitly, and we still leak a name to the surrounding scope (this time it'sa_private_scope
, the name of the function-serving-as-a-scope).By using a function expression and immediately calling it, we avoid this second name pollution:
Now the only thing defined in the outer scope is
myFunction
. The anonymous function that serves as a scope forhi
has no name it could pollute the surrounding scope with.Finally we can clean it up a bit by using return values, so we don't have to mention
myFunction
twice:(This also saves us a pair of
(
)
because thefunction
keyword doesn't appear at the beginning of a statement anymore.)