IIFE Pattern in JavaScript

IIFE Pattern in JavaScript

Learn about what’s the IIFE pattern, how it can be used to improve your code, and some advanced usage

·

3 min read

In JavaScript, functions have their own lexical scope. So variables defined inside it are scoped within that function.

IIFEs are a clever way of using this feature whenever you want a separate environment for your operations (behaviors) for a short moment. They aren’t like functions that could be called multiple times. It’ll run only once. This also helps to avoid name collision without creating unnecessary functions.

IIFE has 2 parts - function expression and invocation.

// 👇🏽 Function expression      👇🏽 Invoking the function
(() => { console.log("hi") }) ();

You can use different ways for writing a function. For example:

// Arrow function
(() => { console.log('hi') })(); // hi

// Anonymous
(function () { console.log('hi') })(); // hi

// Named function
(function greeting() { console.log('hi') })(); // hi

The function greeting isn’t a function declaration because the statement starts with ( and not the function keyword.

Other ways for turning a function declaration into an expression are by putting the + unary operator in front of the function OR ~, ! OR the lesser known but still important delete and void operators.

+function greeting() { console.log("hi"); };

delete function greeting() { console.log("hi"); };

Let’s look at some of the practical use of this pattern.

https://media.giphy.com/media/fxICg09En28tW/giphy.gif

Encapsulation and Name collision

Sometimes it may happen that you want to separate some operations and identifiers to avoid polluting the outer scopes and name collisions.

var food = "🍕";

(function IIFE() {
  var food = "🥦";
  console.log(`I don't like ${food}`);
})();

console.log(`I like ${food}`);

// Output
// I don't like 🥦
// I like 🍕

In the above example, using IIFE we were able to separate our operations of printing the disliked food from the outer scope and also avoid name collision for the identifier food.

Using IIFE in a try-catch block

Since IIFE is an expression we can use it in a statement. We can use IIFE for returning things that are statements into an expression. try-catch is a statement so it can’t be a wrapper around parentheses () like an expression, so the other thing we can do is put it inside an IIFE.

var food = (function getFood() {
  try {
    return fetchFood();
  } catch {
    return "🍞🍞🍞";
  }
})();

console.log(food); // 🍞🍞🍞

This is less common. Without IIFE:

var food;

try {
  food = fetchFood();
} catch {
  food = "🍞🍞🍞";
}

console.log(food); // 🍞🍞🍞

Let’s level up!

https://media.giphy.com/media/eKIXKFcp4oibK/giphy.gif

Advance Usage

Using IIFE pattern to create a module. Since functions are objects (special kinds) and have their own lexical scope, we can use them to encapsulate data and methods together and thus we create a module.

var food = (function Module(food) {
  /** Things we want public */
  var publicAPI = { eat };
  return publicAPI;

  function eat() {
    console.log(`Eating some ${food}`);
  }

  /** Private method */
  function cook() {
    console.log(`Cooking ${food}`);
  }
})("pie");

console.log(food);
food.eat();

// Output
// { eat: [Function: eat] } <-- doesn't have the `cook` method
// Eating some pie

Conclusion

IIFEs are amazing to execute set of operations in a separate environment for once. Embrace it and write quality code. If you liked this post then do 👍🏼 like and give your 🎙 feedback. ✅ Follow to stay up to date with my new posts.

https://media.giphy.com/media/12noFudALzfIynHuUp/giphy.gif