Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
June 21, 2021 07:39 am GMT

Beginner JavaScript - 10 - Immediate Invoked Function Expressions

Hey everyone ,

In this article, let us discuss about Immediate Invoked Function Expressions (IIFEs) in JavaScript. This is the tenth part of my Beginner JavaScript Series on Dev.

Immediately Invoked Function Expressions - A complete picture

Alt Text

Immediately Invoked Function Expression, or IIFE for short is a function that is executed immediately after its created.
A key point to note here is that it has nothing to do with any event-handler for any events (such as window.onload etc.)

It has nothing to do with any event-handler for any events (such as document.onload).

// Syntax (arguments are optional)(function(argument_one, argument_two,...){  // code goes inside here (function body) })(value_one, value_two, ...);

Consider the part within the first pair of parentheses: (function(){})(); this is what is called as a regular function expression. Also if you observe the syntax carefully in the end we have an invocation parenthesis to invoke the function.

Now the thing you need to understand here is that this pattern is often used when trying to avoid polluting the global namespace, because all the variables used inside the IIFE (like in any other normal function) are not visible outside its scope.

(function(){  // all your code here  const foobar = function() {};  window.onload = foobar;  // ...})();// foobar is unreachable here (its undefined)

In the case of IIFEs, the function is executed right after it's created, not after it is parsed. The entire script block is parsed before any code in it is executed. Also, parsing code doesn't automatically mean that it's executed, if for example the IIFE is inside a function then it won't be executed until the function is gets invoked.

So this is it for this one. I do have a video on IIFEs as well. So make sure to check that if interests you :

If you are looking to learn Web Development, I have curated a FREE course for you on my YouTube Channel, check the below article :

Looking to learn React.js with one Full Project, check this out :

Follow me on Twitter : https://twitter.com/The_Nerdy_Dev

Check out my YouTube Channel : https://youtube.com/thenerdydev


Original Link: https://dev.to/thenerdydev/beginner-javascript-10-immediate-invoked-function-expressions-3dnn

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