An Interest In:
Web News this Week
- April 20, 2024
- April 19, 2024
- April 18, 2024
- April 17, 2024
- April 16, 2024
- April 15, 2024
- April 14, 2024
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
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 :
(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
Original Link: https://dev.to/thenerdydev/beginner-javascript-10-immediate-invoked-function-expressions-3dnn
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To