The JS Bifrost — Understanding the coding pattern called (IIFE)

The most popular idiom for function expression

Mrunal Kamat
Globant
4 min readSep 16, 2020

--

Welcome to The JS Bifrost, your pathway to rock-solid foundation for God-level JavaScript. This is the next article in the series. This article is about one of the most popular coding pattern called “iffy”, which is a JavaScript function that executes immediately after creation.

Definition

An IIFE is a coding pattern called an Immediately Invoked Function Expression which is a way to execute a JavaScript function immediately after it is created. Also pronounced as “iffy.” Let’s look at the traditional and more widely used syntax used to declare an IIFE.

The ES6 way: 
(() => {
/* statements */
})()
The ES5 way:
(function() {
/* statements */
})()

Syntax

Let’s break down the syntax for the above example step by step:

  1. When JavaScript encounters a function keyword in a valid statement, it expects that a function definition/declaration is going to take place. To stop the JavaScript engine from throwing a syntax error, a function expression is created by wrapping the function definition inside parentheses. The wrapping parentheses will be internally considered as an expression.

2. Alternatively, there is another variation of writing an IIFE:

!function() {    
alert("Hello, I am an IIFE!");
}();
// Prints Hello, I am an IIFE!

The “!” operator as a prefix, will tell JavaScript that “Anything after the not operator is part of an expression. (You can replace “!” with any unary operator which will make that function into an expression.) But this variation will not return any value from the IIFE.

3. At the end of the definition, add another pair of parentheses which are called the invoking parentheses and a semicolon. The invoking parentheses is what tells the compiler that the function expression has to be executed immediately.

Example1:
(function() {
/* statement */
}());
Example2:
(function() {
/* statement */
})();

“()”, for invoking the function expression is either placed inside or outside the wrapping parentheses for the function expression.

Anonymous or Named?

IIFE functions are anonymous functions — As per the definition, anonymous function has no identifier. This is a function expression which does not require a name.

The wrapping parentheses will treat what is inside, as an expression and will immediately evaluate to return a value.

They can also be named functions. However, having a name is unnecessary as IIFE’s cannot be referred/invoked more than once after their execution. (Apart from function name showing up in stack-traces).

(function foo() {  
/* statements */
})();

A quick example to show that IIFEs can also take arguments when they are invoked. We are now passing an argument to the IIFE when we execute it.

(function(myTxt) {    
console.log(myTxt);
})(“Hello!, I am an IIFE”);
// Prints Hello!, I am an IIFE

Why?

IIFE’s are useful because they don’t pollute or overwrite the global object and they are a simple way to isolate variable declarations.

  • Data Privacy — IIFEs have their own scope i.e. the variables you declare in the Function Expression will not be available outside the function.
(function () {  
var myName = "John";
})();
// Variable myName is not accessible from the outside scope
// myName throws "Uncaught ReferenceError: myName is not defined"

These variables are now scoped to the containing function because var variables will be function-scoped and they will not be available in the global scope.

  • No Name Collision — Functions and variables defined inside IIFE do not conflict with other functions & variables even if they have same name.

If you have many global variables and functions with the same name, the JavaScript engine will only release the memory allocated for them until when the global object loses the scope. The global variables and functions will likely cause name collisions. With the use of IIFE, defining variables inside functions or between curly braces makes them inaccessible to the global namespace which will help minimise the pollution of the global scope.

Assigning the IIFE to a variable stores the function’s return value, not the function definition itself.

var MyVar = (function () {   
var myName = "John";
return name;
})();
// Immediately creates the output // "John"

ES6 Block scope is the new IIFE

In ES6, const and let keywords allow developers to declare variables in the block scope, which means those variables exist only within the corresponding block. When you declare a global variable using the var keyword, you are adding that variable to the property list of the global object. In the case of the web browser, the global object is the window. However, when you use the let or constkeywords to declare a variable, that variable is not attached to the global object as a property. Hence the variables will have their own scope and will not allow you to redeclare them making your data private.

{    
const myName = 'John';
console.log(myName);
}

This will help when you want to make your code private where nothing leaks into the global scope of the window.

Conclusion

The most common use cases for IIFE’s are:

  • Creating private variables and functions.
  • Minimizing the pollution of the global scope due to name collisions.

That’s all there is to know about IIFEs to start using them in your code.

Watch this space to make more progress on your way to ‘God level JavaScript’ with ‘The JS Bifrost’.

--

--