Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
July 27, 2021 10:12 am GMT

8) What is IIFE in JavaScript

IIFE: Immediately Invoked Function Expression

It is a JavaScript Function that runs as an when it is defined.

Syntax of IIFE
image

Let's talk about the two parenthesis in the above syntax.

( function() {} )

Outer parenthesis '()'
While executing JavaScript code, whenever the compiler sees the word function, it assumes that we are declaring a function in the code.
Therefore, if we do not use the first set of parentheses, the compiler throws an error because it thinks we are declaring a function, and by the syntax of declaring a function, a function should always have a name.

So, instead of getting error, we have to use the first set of parenthesis that tells the compiler that this function is not the function declaration but it's function expression.

( function() {}) ();

Right-end side parenthesis '()'
So, IIFE states that the function should invoke immediately as soon as it is defined.
And as we know to run a function we need to invoke it.
If we don't invoke it, function declaration is returned.
That's why this second parenthesis is just for invoking.


Original Link: https://dev.to/myk/8-what-is-iife-in-javascript-1bng

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