DEV Community

loading...

Beginner JavaScript - 10 - Immediate Invoked Function Expressions

The Nerdy Dev
Building products is my profession, Creating content is my passion. We believe that Education should be freely accessible to everyone and no one should be deprived of it.
・Updated on ・2 min read

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 it’s 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, ...);
Enter fullscreen mode Exit fullscreen mode

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 (it’s undefined)
Enter fullscreen mode Exit fullscreen mode

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

Discussion (0)