This content originally appeared on DEV Community and was authored by The Nerdy Dev
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
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, ...);
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)
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 :
(2021) - Web Developer Full Course : HTML, CSS, JavaScript, Node.js and MongoDB
The Nerdy Dev ・ Apr 28 ・ 2 min read
Looking to learn React.js with one Full Project, check this out :
Learn React with one BIG Project [NOTES included] - Demo and Video Link
The Nerdy Dev ・ Jun 10 ・ 1 min read
?? Follow me on Twitter : https://twitter.com/The_Nerdy_Dev
?? Check out my YouTube Channel : https://youtube.com/thenerdydev
This content originally appeared on DEV Community and was authored by The Nerdy Dev
The Nerdy Dev | Sciencx (2021-06-21T07:39:07+00:00) Beginner JavaScript – 10 – Immediate Invoked Function Expressions. Retrieved from https://www.scien.cx/2021/06/21/beginner-javascript-10-immediate-invoked-function-expressions/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.