loading...
Cover image for What is an IIFE?

What is an IIFE?

shoupn profile image Nick Shoup ・3 min read

This post was originally published on my blog Fundamentals of Code

Feeling a Little IIFE?

I have covered modules in previous posts, and this week I wanted to create a short synapse of Immediately Invoked Function Expressions or often referred to as IIFE (pronounced if-ee or iffy ) statements. These are similar to modules in that they help to encapsulate variable and eliminate the potential for global pollution of values. If you are curious about some additional examples and how to use the module pattern check out my previous post, especially the revealing module portion.

Example of An IIFE

Let's take a look at what an IIFE looks like, and then dissect further.

(function(){
  const iife = "IIFE"
  console.log(iife)  
})(); //

console.log(iife)//reference error exception will be thrown

Notice the basic creation of an IIFE looks like the following (function(){//...code goes here}());. This is all that is needed to wrap our code in the function call. Don't forget the trailing anonymous function (). When the browser's javascript compiler parses our code, it will execute this snippet immediately. In the module pattern, we are assigning this IIFE declaration to a variable to use later, and returning or exposing public functions and properties.

Working on Global Properties

A use case for IIFE's is when we want to work on a global variable without modifying the variable. We can do a variety of things with this in the IIFE, it has a closure of its own and accepts a parameter in the callback at its tail. Notice in this example, We declare a variable, and then pass it in at the end. The IIFE has a parameter that will then work on the passed in a variable without modifying the global variable. Pretty nifty right!

let x = 0;

(function(y){
  y = y + 1;
  console.log(`y =  ${y}`);//1
  //note: we have modified y as a parameter passed in without modifying our global variable.
  console.log(`inside IIFE x =  ${x}`);//0
})(x);
console.log(`x =  ${x}`);//0

Another thing to consider is passing in the window and document objects.

(function(window, document ) {

  // You can now reference the window and document in a local scope
console.log(document)
}(window, document));

Return values from an IIFE's

You can also return values from an IIFE in the following way.

const val = (function(){
    return "A value from our IIFE"
}());

console.log(val);//Note that you can also return much more complicated objects if needed

This is the power if IIFE's and fundamentally how the revealing module pattern works. For an example of that please refer to my previous post on modules. As I mentioned earlier this pattern is used extensively by modules, as it enforces a self-contained scope within the closure. This is key to for this pattern as it allows for them to be reusable, maintainable, and reduce namespace pollution.

Legacy or Die!

I understand too, that this pattern is not as widely used within more modern applications, however, you should be aware of this as it will appear in older code bases, and there still may be some use cases for this pattern.

Once again thanks for reading and I hope you find this useful. Please share and comment. Let me know if you still use IIFE's!

Posted on Mar 4 '19 by:

shoupn profile

Nick Shoup

@shoupn

GIS Developer, outdoor enthusiast, cryptocurrency/blockchain enthusiast, father, and husband. I really just want to share my passion for coding with others.

Discussion

markdown guide
 

There are useful use for IIFE in modern apps. For instance when you need an expression and don't want to define a separate function (e.g for clarity, or to have access to variables through the closure instead of passing them as arguments).
In react for example, if you need some piece of logic within jsx tags and can't only rely on ternary/boolean logic, an IIFE can be handy.
In that regard, IIFE are an alternative to do-expressions (github.com/tc39/proposal-do-expres...).

 

Thanks, I have not done much in the world of React, outside of my own curiosity. I have seen and used IIFE's pretty regularly in some older angularJs apps. Used mostly for the ability to work on some logic without affecting the global window of properties. I'll have to take a look at React's do-expression.

 

React is just one example where IIFE can be useful though the use case I was referring to applies anywhere where you need/want an expression and need to perform some logic.
do-expressions is a new js feature but isn't limited to react either.

Gotcha, re-read what you stated, makes sense when thinking about something like a ternary operation not quite fitting the bill.

 

When we use namespace in typescript and compile it into js, it will use IIFE also as its pattern.

Personally I also like IIFE so much because we can breakdown 1 function become simple function without declaring lot of public function.

 

I am actually going to write about namespaces in JavaScript next!

 

IFFE is still around for many legacy code based - it would be a great addition for the article to talk through the performance implications for using IFFE's with JS. I believe Kyle Simpson talks about it in his YDKJS series!

Not taking away from the post or from IFFE's, just felt it is important for us to keep in mind :)

 

As someone who came from python, where the convention is to define a main function, this looks like the ugliest design pattern in the world. It never ceased to amaze me how this one has stuck around. Thank God for ES6 I guess..
Anyway great article with very clear examples!

 

Thanks Dor! I agree it can be a bit obtuse to look at. What always gets me is having to go to tail of the code to see what parameters were being passed in from outside the IIFE's scope.

I agree that ES6 has definitely made this cleaner and easier to understand with classes and imports. However, I was looking around briefly to see if ES6 modules are actually a syntactic sugar over this, but did not come up with anything yet.