Re this lecture
const myFunction = (
function () {
const hi = 'Hi!';
return function () {
console.log(hi);
}
}
)();
Re the above code he says ‘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.’
in order to print ‘Hi!’ to the console I run myFunction();
if we type console.log(hi), in the global scope we get undefined
- no problems here the above behavior is according to what he explained, however…
if we modify above code to not use the IIFE for example:
const myFunction =
function () {
const hi = 'Hi!';
return function () {
console.log(hi);
}
}
We can execute the above by typing
myFunction()();
and now same as before type console.log(hi) in the global scope it also returns ‘hi is undefined’. Is this not proof that this way also does not pollute the global scope? in the same way using the IIFE does not. Therefore I do not understand what he means when he says
‘the IIFE wraps up the code nicely so that we don’t pollute the global scope.’
because as you’ve seen just take away the IIFE and we achieve the same result. Can someone please explain to me what he means.