Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
September 18, 2022 03:56 am GMT

Javascript: IIFE - Immediately Invoked Function Expression

Regular function in javascript is:

// function declarationfunction myFunction() {    console.log('I am normal JS function');}// function invocationmyFunction();> I am normal JS function

Ok. What is function expression?

Expression - evaluate to a value.

const value = 1;const comeToThePoint = value === 1 ? 'yes' : 'no';

the above one is an expression statement that evaluates to value yes. So, what?

in the same way, We can assign a function to a variable which we call function expression.

const myExpressiveFunction = function(a, b) {    return a + b;}myExpressiveFunction(10, 20);> 30

Note it: The above function has no name hence it is an anonymous function. To use the above function you need to call using the variable name.

ook. What is immediately invoked? Hmm. Maybe I get it as it gets executed as soon as defined, right?

Exactly. Which we called an Immediately Invoked Function expression and it can only be achieved using anonymous functions.

Cool. What next?

Let's understand the importance of parenthesis in javascript.

// it is an expression that you can put inside parentheses and it will get executed.(a = 10);// declaration inside parenthesis results in SyntaxError(var a);

in the same way, if we put the above function expression inside parentheses becomes IIFE.

Example:

(function(a, b) {    return a + b;})(10, 20);

it can be shortened by arrow functions as:

((a,b)=>a + b)(10, 20);

We are done!

You can follow me here: https://twitter.com/urstrulyvishwak


Original Link: https://dev.to/urstrulyvishwak/javascript-iife-immediately-invoked-function-expression-3i2a

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