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.

Tiugo image

Modular, Fast, and Built for Developers

CKEditor 5 gives you full control over your editing experience. A modular architecture means you get high performance, fewer re-renders and a setup that scales with your needs.

Start now

Top comments (0)

Tiugo image

Fast, Lean, and Fully Extensible

CKEditor 5 is built for developers who value flexibility and speed. Pick the features that matter, drop the ones that don’t and enjoy a high-performance WYSIWYG that fits into your workflow

Start now

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay