Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
December 25, 2021 05:24 pm GMT

What is IIFE in JavaScript ?

Sometime in JavaScript we need a function that executes only once and never again. Basically a function that disappears right after its called once. How can we achieve this? for example we could do this:

const func1 = function(){             console.log('this function will never run again!`)                } func1();

But we definitely can call this func1() again if we want. This is NOT what we want to do. We want to execute a function immediately without having to save it somewhere.
So this is how we do that,
we simply write the function expression itself without assign it to any variable.

function(){console.log('This function will never run again')}

if we run this, we would get an error function statements require a function name an that's because JavaScript expects a function statement, but we simply start a new line of code with the function keyword.

Here we can still trick JavaScript into thinking that this is just an expression. We do that by simply wrapping all of this into GROUPING OPERATOR().

(function(){   console.log('This is will never run again!')});

so we basically transform the previous statement into an expression. But the function didn't execute yet. To execute the function we need to call it like this (adding '()' next to it, like we do with regular function call).

(function(){   console.log('This is will never run again!')})();

So we create a function expression and we immediately call it. which is why this pattern is called Immediately Invoked Function Expression(IIFE).

The same would also work for an arrow function this way.

(() => console.log('This function will never run again!'))();

This will also never run again.

so this is not really a feature, of the JavaScript.

it's more of a pattern, that some developers come up with and it is widely used.

This design pattern is also known as a Self-Executing Anonymous Function.
Self-Executing -> it executes the moment it is created.
Anonymous -> it has no name and is not stored variable.


Original Link: https://dev.to/officialkamran/what-is-iife-in-javascript--45p0

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To