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)

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay