DEV Community

Ansh Mittal
Ansh Mittal

Posted on

What is IIFE in JavaScript.

In this article you will learn about the IIFE in javaScript.
All beginners level developers should know atleast this knowledge about the IIFE.

IIFE, or Immediately Invoked Function Expression, is a self-executing anonymous function in JavaScript. As the name suggests, it is a function that is invoked immediately after it is defined, without the need for an explicit function call.

The syntax for defining an IIFE is as follows:

Image description

In this example, we define an anonymous function, wrap it in parentheses to make it an expression, and then immediately invoke it using the () at the end.

What is the Benefits using IIFE.

The primary benefit of using IIFE is that it helps to avoid polluting the global namespace with variables and functions. By wrapping code inside an IIFE, we create a private scope where variables and functions declared inside it are not accessible outside of it. This is useful for preventing naming collisions with other variables and functions defined in the global scope.

Image description

In this example we are creating a IIFE function. Inside this we are created a count variable and increament function. This increament function increments the value of counter.
After this we are calling a increament function and then print the counter value and what's the output of this yes 😁 you are right it's 1.

But what happened if we try to print outside of the function.
It's getting a ReferenceError because IIFE not saves data globally. It's safe data inside his private scope so we can't use outside of this function.

I hope you understand what is IIFE and Why this it is used.
If you like this article so don't forget to comment below 👇 of this article.

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay