DEV Community

Heru Hartanto
Heru Hartanto

Posted on

What is an IIFE (Immediately Invoked Function Expression) and Why Should You Care?

An (IIFE) Immediately Invoked Function Expression is a function that executed as soon as it’s defined.
It’s a common design pattern that helps create a private scope and avoiding polluting the global scope.

(function () {
  // Code inside IIFE
})();
Enter fullscreen mode Exit fullscreen mode

The function declare inside parentheses and trailing () immediately invoke it.

This can be useful when you need to fetch data immediately after the page loads, here the example:

(async function () {
  try {
    let response = await fetch("https://jsonplaceholder.typicode.com/posts");
    let data = await response.json();
    console.log(data);
  } catch (error) {
    console.error("Error fetching data:", error);
  }
})();
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

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

👋 Kindness is contagious

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

Okay