javascriptsyntaxscopeblockiife

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?


Solution

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