Web Reflex 🥊 : Get Triggered Immediately

Abdul Baasith
2 min readJul 24, 2024

--

Hi There,
If your having a fight you might have quick reflex , What if i tell javascript also can do a immediately invoked function. The Immediately-Invoked Function Expression, or as the cool kids call it, IIFE (pronounced “iffy”).

IIFE — Immediately-Invoked Function Expression

Once upon a time, in the land of JavaScript, there was a function so clever and so sneaky that it could execute itself without waiting for an invitation. Like us sneaking into classrooms late after lunch break 🥘.

(function() {
console.log("i will run without even being invoked!");
})();

The first time i encounter IIFE, i was surprised. its was used for a async function. Normally we define a async function and then call it just makes sense to do it by itself rather than just defining it and calling the function.

In JavaScript, variables declared inside a function stay local to that function, protected from the prying eyes of the global scope. IIFE used this to its advantage, creating a safe haven for its variables.

(function() {
var secret = "Baasith";
console.log(secret); // Baasith
})();

console.log(typeof secret); // undefined

Leave the old school function 😅

we can use IIFE with arrow functions. As JavaScript evolved, so did IIFE. When arrow functions swooped into town, IIFE embraced the new syntax

(() => {
console.log("I am an arrow function ! :haha just log me ");
})();

We can use the IIFE for different task it depends based on your use case

wondering how did i come across this function is with a code review based on my colleges suggestion. it was on a async api call which i made a function inside useEffect and called it at the same spot. 😅

(async () => {
try {
// Your async code here
const response = await fetch("some link");
const responseData = await response.json();
console.log(responseData);
} catch (error) {
console.error(error);
}
})();

Hope the read was helpful !!! 😄

Happy reading

--

--

Abdul Baasith
Abdul Baasith

Written by Abdul Baasith

Hi there i'm Abdul Baasith, A passionate Software Engineer . If your tool is a hammer then every problem look like a nail

No responses yet