IIFE
An IIFE is (Immediately Invoked function Expression) that runs as soon it is defined.
(function () {
var number = Math.random() * 10
console.log(number >= 5)
})()
It is a design pattern also known as self executing anonymous function and contains two major parts
The first is the anonymous function with lexical scope enclosed withing the grouping selector (). This Prevents accessing variable withing the IIFE idiom as well as polluting the global scope.
The second part is the Immediately invoked function expression (). through which javascript engine will interpret the function
uses of IIFE
(function () {
var Num = 17;
console.log(1 + Num)
})
console.log(Num) // This will throw an error
- A common use of an IIFE is that a function or a Variable declare inside of a IIFE block cannot be accessed outside of an IIFE block, thus preventing global scope from getting polluted. Also help us manage memory in efficient way.
Top comments (9)
If you're not using jQuery or one of the JS frameworks, IIFE is absolutely necessary to make sure your code self-executes on page load and that you contain your code within its own scope. It's definitely very useful and for the life of me I always forget the acronym so when i actually need it, i can't freaking find it lol.
yes I just learn about it and knowing that how powerfull it can be!
Is it preventing scope pollution the only motivation to use these?
You could also use an IIAFE (immediately invoked async function expression) to emulate top-level-await.
Thank you. I think you should expand your article explaining the uses and the reasons for using it. Otherwise the audience will probably only be the people that already know about your content.
This is my first blog post and I will definetely expand this post thank you for your comment Guillermo🙂
actually I'm following the course in which he teach me about IIFE so I just wrote that here I will learn about IIAFE and expand this post as soon as possible
yes and also for making our code more private
I will learn about that as soon as possible thank you!