Const vs IIFE

Hi!

Something I’ve been pondering… I saw a video a while back on IIFE in JavaScript and how it is used to create a variable inside the scope of an “immediately invoked function expression” so that the variable won’t be overwritten.

This video was a couple of years old and since I haven’t come across IIFE until now, my first thought was that an IIFE nowadays would be unneccessary compared to a const.

Is this the reason why IIFE isn’t taught as frequently, or why is IIFE less common?

Any input is highly appreciated,

Thanks!

It really is just a question of scope. If you have a single function that only needs executed once, and it requires info that isn’t needed by any other part of the program then it makes sense to use IIFE. Declaring a const variable (assuming it’s declared outside the function) would mean that variable will remain in the namespace and could in theory cause conflicts. With best naming practises this shouldn’t really be an issue anyway, but it’s certainly a consideration to be made. See the below codebytes for a comparison.

const name = "Adam"; const greeting = name => { console.log(`Welcome ${name}!`); } greeting(name); // console.log(name);
(name => console.log(`Welcome ${name}!`))("Adam"); // console.log(name);

You can see that in the first one, we declare a variable, declare the function and then call the function with the variable. The variable name now exists forever in the namespace of that file, and cannot be renamed as it is a const. Also, we should in theory only need to greet someone once within a script run, right? Say this was a greeting on a webpage, the webpage would be reloaded if someone new logged in, thus the greeting would be rerun each time.

The IIFE takes away all the extra stuff, and condenses the full first script into a single line with no variables. The output is still the same, however nothing is stored in the namespace as we can see from the console.log() in the second codebyte.

As for why they are uncommon, I think that’s more just because JS is pretty much always used in webpages, and it’s very rare you don’t need to use an element more than a single time on first webpage load. Webpages are dynamic and rely a lot on user input, so generally there’s not a ton of necessary application for this. However it’s always good to know just in case it ever does prove useful for you.

2 Likes

Awesome explanation, Adam! Thank you so much!
I’m going to read through it a couple of times and also tinker around with IIFE to understand them and their uses better.