Why the following code doesn’t work as an IIFE?

Hi, this is a interview question and also is good to know what a IIFE is.

IIFE means – Immediately Invoked Function Expression.

And the idea using IIFE is if we write a function then immediately run that function.

Why the following code doesn’t work as an IIFE?

function foo() {
    console.log('Running!')
}();

Result:

Well, Javascript will read the code like this and will say: oh! this doesn’t make any sense to me!

function foo() {} // 1 function statement declaration
(); // 2 call a function that doesn't have a name...hmm

So, instead this you need to convert the function as an “expression” not as “statement” and to do that we need to wrap the function between parenthesis (function …) (); and Javascript will interpret this pair of parentheses as an expression.

(function foo() {
  console.log("Running!");
})();

Result:

Why would I ever use one?

Well, you can use to control variable scope, this means that all the variables inside a IIFE would’t be available outside that function.

By Cristina Rojas.