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