DEV Community

DIWAKARKASHYAP
DIWAKARKASHYAP

Posted on • Edited on

2 1 1 1 1

What is IIFE in Javascript ? (important interview question)

An IIFE, or Immediately Invoked Function Expression, is a JavaScript function that executes immediately after it is defined. It provides a way to create self-contained blocks of code that don't interfere with the global scope. By invoking the function immediately, it allows for encapsulation and private variable scope.

(function() {
    //write any code , it will automatically run 
  console.log("Hello world");
})();
Enter fullscreen mode Exit fullscreen mode

in this example, an anonymous function is defined and invoked immediately by wrapping it in parentheses. It executes instantly without requiring explicit invocation elsewhere in the code.

(function(name) {
  console.log("Hello, " + name + "!");
})("Diwakar");

Enter fullscreen mode Exit fullscreen mode

in this example, the IIFE takes a "name" argument and logs a personalized greeting. the argument "Diwakar" is passed when invoking the IIFE.

use case:-

1- Avoiding global namespace pollution

2- compatibility with older javascript

3- Encapsulating code

4- Modular Pattern

Thank you for reading, please follow me on Twitter, i regularly share content about Javascript, and React and contribute to Opensource Projects

Twitter-https://twitter.com/Diwakar_766

Github-https://github.com/DIWAKARKASHYAP

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

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

Okay