As I understand it, the IIFE pattern is a work around to the fact that ES5 and below do not have a way to create block scopes. By wrapping everything in a function and immediately invoking it, we can create a scope.
Now that let
and const
will gain support by more the browsers, does this reduce the need for something like the IIFE pattern?
An IIFE is a good way to secure the scope. You can use IIFEs to prevent global variables' definition issues, alias variables, protect private data, and avoid conflicts of using many libraries that export the same object name.
Several readers criticized the post for being out of date, though, arguing that block-scoped variables as introduced by ECMAScript 2015 make IIFEs obsolete. Quite the contrary is true — the IIFE pattern is not obsolete at all!
IIFEs are very useful because they don't pollute the global object, and they are a simple way to isolate variables declarations. An Immediately-invoked Function Expression (IIFE for friends) is a way to execute functions immediately, as soon as they are created.
This is because both instances are treated as different variables since they have different scopes. This fact makes let a better choice than var . When using let , you don't have to bother if you have used a name for a variable before as a variable exists only within its scope.
Yes, blocks are going to replace IEFEs, as soon as block-scoped declarations (functions, let
/const
/class
) become widely adopted. You need a scope, e.g. for a closure? Here you have a block, be it a loop body or just part of a statement list.
However, there is still one application of IEFEs that blocks cannot replace: the module pattern. Blocks don't have return values, and mutating higher-scoped variables is ugly, so we will still see function expressions in the creation of objects that need private state:
const example = (() => { … return …; }());
Although browser's may begin supporting this, there will always be some random browser that is outdated or is not planning support for this. until it has become standard in all major browsers, it is still recommended that you continue going on with your IIFE pattern until you find it on all majorly used browsers. something you could do is have a script (or google analytics) send information on whether this is undefined or not and until you get at least around 90% of it saying it is not undefined you should continue with IIFE.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With