IIFE function in javascript

Immediately Invoked Function Expression

As a JavaScript developer, you may have heard of Immediately Invoked Function Expression (IIFE) before, but may not fully understand what it is or how it works. In this article, we’ll dive into IIFE, discussing what it is, how to use it, and its benefits.


When writing JavaScript code, it’s essential to understand different programming concepts and techniques, including Immediately Invoked Function Expressions (IIFE).

A self-executing anonymous function that runs immediately after being defined is known as an IIFE. It’s a unique way of writing functions in JavaScript that allows you to execute a function immediately after defining it.

What is an Immediately Invoked Function Expression (IIFE)?

An Immediately Invoked Function Expression (IIFE) executes immediately after its definition, without requiring explicit calling. It’s an anonymous function enclosed in parentheses and followed by another set of parentheses to call it immediately. The syntax of an IIFE looks like this:

   // code goes here

The outer set of parentheses is used to enclose the function expression, and the inner set is used to call the function. This syntax may look confusing at first, but it’s essential to know how it works and its benefits.

How to create an IIFE?

To create an IIFE, you need to wrap your function in parentheses and call it immediately using another set of parentheses. Here’s an example of how to create an IIFE:

   console.log('Hello World!');

This will output ‘Hello World!’ to the console immediately after the function is defined. You can also pass arguments to the function by adding them to the inner set of parentheses. For example:

   console.log('Hello ' + name + '!');

Benefits of using IIFE

There are several benefits to using IIFE, including:

1. Avoiding naming conflicts

Since IIFEs are anonymous functions, they don’t create a new variable scope. This helps to avoid naming conflicts with other variables in your code.

2. Encapsulating code

IIFEs help to encapsulate code by creating a private scope for your function. This means that variables declared inside the IIFE are not accessible outside of it, helping to prevent variable name collisions.

3. Modularizing code

IIFEs can help to modularize your code, making it easier to manage and reuse. By wrapping your code in an IIFE, you can create a self-contained module that can be used in other parts of your application.

4. Performance optimization

By executing code immediately, IIFEs can help to optimize the performance of your application. This is because there’s no need to call the function explicitly, which can save time and resources.

Follow Us on


Read More

Thank You

Related Post

Leave a Reply

Your email address will not be published. Required fields are marked *