DEV Community

Cover image for What is an IIFE in Javascript?
Amol Shelke
Amol Shelke

Posted on • Edited on

What is an IIFE in Javascript?

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)
})()
Enter fullscreen mode Exit fullscreen mode

It is a design pattern also known as self executing anonymous function and contains two major parts

  1. 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.

  2. 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 

Enter fullscreen mode Exit fullscreen mode
  • 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)

Collapse
 
ravavyr profile image
Ravavyr

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.

Collapse
 
amolshelke2 profile image
Amol Shelke

yes I just learn about it and knowing that how powerfull it can be!

Collapse
 
guillep2k profile image
Guillermo Prandi

Is it preventing scope pollution the only motivation to use these?

Collapse
 
lexlohr profile image
Alex Lohr

You could also use an IIAFE (immediately invoked async function expression) to emulate top-level-await.

Collapse
 
guillep2k profile image
Guillermo Prandi

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.

Thread Thread
 
amolshelke2 profile image
Amol Shelke

This is my first blog post and I will definetely expand this post thank you for your comment Guillermo🙂

Collapse
 
amolshelke2 profile image
Amol Shelke • Edited

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

Collapse
 
amolshelke2 profile image
Amol Shelke

yes and also for making our code more private

Collapse
 
amolshelke2 profile image
Amol Shelke

I will learn about that as soon as possible thank you!