An Interest In:
Web News this Week
- March 30, 2024
- March 29, 2024
- March 28, 2024
- March 27, 2024
- March 26, 2024
- March 25, 2024
- March 24, 2024
8) What is IIFE in JavaScript
IIFE: Immediately Invoked Function Expression
It is a JavaScript Function that runs as an when it is defined.
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
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To