Skip to content


What is an IIFE in JavaScript?

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:

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.

More like this

Start typing a keyphrase to see matching snippets.