"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > What is an IIFE (Immediately Invoked Function Expression) and Why Should You Care?

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

Published on 2024-11-02
Browse:475

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
})();

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);
  }
})();
Release Statement This article is reproduced at: https://dev.to/elukuro/what-is-an-iife-immediately-invoked-function-expression-and-why-should-you-care-2cap?1 If there is any infringement, please contact study_golang @163.comdelete
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3