Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: difference between using an IIFE and a block statement

IIFE are mainly used to encapsulate scope

(function () {
    let myVar = 10; // not global
    // ...
}());

but why not just use a block statement?

{
    let myVar = 10; // also not global
    // ...
}

are there other benefits for using IIFE further than scope encapsulation?

like image 631
Lucas Noetzold Avatar asked Aug 31 '25 22:08

Lucas Noetzold


1 Answers

Block statements are a pretty recent feature. And yes, before they were introduced, IIFEs were used instead.

Nowadays I can think of at least one case, when IIFEs are irreplacable. Look at this:

(async () => { const foo = await someAsyncFunction() })()

See? The await keyword can only live in an async function, hence if your await-containing expression is not wrapped by any function, you have to wrap it by an async IIFE.

UPD: this answer is outdated, since top-level await is now available, so no need to use IIFE to wrap it, so there are even less uses for IIFEs now, if any.

like image 70
Nurbol Alpysbayev Avatar answered Sep 03 '25 12:09

Nurbol Alpysbayev