What is an IIFE in JavaScript?

JavaScript, Function · Jun 14, 2021

An Immediately Invoked Function Expression (IIFE for short) is a JavaScript function that is immediately invoked as soon as it's evaluated by the JavaScript runtime. Here's what it looks like alongside a roughly equivalent piece of code:

(function (message) {
})('Hello World');
// LOGS: 'Hello World'

// Equivalent code using named function
function logMessage(message) {

logMessage('Hello World'); // LOGS: 'Hello World'

Remember the "roughly equivalent" part? The only difference is the use of a named function instead of an anonymous one. From this example, it should be easy to deduce the anatomy of an IIFE, breaking it down into its parts:

  • Optional leading semicolon to avoid TypeErrors in cases of minification etc.
  • An anonymous function, containing all the code that we want to invoke.
  • Opening and closing parentheses to wrap the anonymous function.
  • Parentheses to call the function and any arguments to invoke it with.

Note that you can also use arrow functions for IIFEs, if you like. Just make sure to remember the differences between regular and arrow functions in that case. Our previous articles on arrow functions and the this keyword should just about cover them.

// All of these are equivalent, leading semicolon is optional
;(() => console.log('Hello'))();
;(function(){ console.log('Hello'); })();
;(function(){ console.log('Hello'); })();
;(function(){ console.log('Hello'); }());

IIFEs are often used to run some code, while keeping it and its variables out of the global scope. They are often criticized for lack of readability and how they are confusing to beginners. Additionally, they started going out of fashion with the rise of JavaScript modules and transpilers, so they might be less and less common as time goes by.

Written by Angelos Chalaris

I'm Angelos Chalaris, a JavaScript software engineer, based in Athens, Greece. The best snippets from my coding adventures are published here to help others learn to code.

If you want to keep in touch, follow me on GitHub or Twitter.

More like this

  • Converge branching functions

    Converges a list of branching functions into a single function and returns the result.

    JavaScript, Function · Jan 7, 2021

  • Rearrange function arguments

    Creates a function that invokes the provided function with its arguments arranged according to the specified indexes.

    JavaScript, Function · Oct 22, 2020

  • Throttle function

    Creates a throttled function that only invokes the provided function at most once per every wait milliseconds

    JavaScript, Function · Oct 13, 2021