Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will const and let make the IIFE pattern unnecessary?

Tags:

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?

like image 498
Kyle Pennell Avatar asked Nov 05 '15 00:11

Kyle Pennell


People also ask

Should I use IIFE?

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.

Are IIFE still used?

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!

Why is IIFE important?

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.

Is Let always better than VAR?

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.


2 Answers

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 …; }()); 
like image 71
Bergi Avatar answered Nov 10 '22 07:11

Bergi


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.

like image 42
puppy0cam Avatar answered Nov 10 '22 08:11

puppy0cam