IIFE avoids Global pollution?

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.

Yes, but you’re creating and returning a new function every time you invoke myFunction()().

The first myFunction can be just invoked as myFunction(), because it’s just referencing returned function definition of the anonymous function that’s stored in myFunction

Additionally, if you’re trying to use a closure, you’ll run into situations where you want the const hi to persist between function invocations. For instance, let’s imagine a function that keeps track of the number of times it was invoked

const invokedNTimes = (function(){
  let i = 0;
    return function(){
      i = i + 1;
      console.log(i)
    }
})()

if you enclose it in an IIFE, it’ll log 1 the first time you run it, then 2, then 3, and so on.

If you don’t, you’ll just get 1 every time.