1

For years I've always written IIFEs like this:

(function () {
    console.log("hi");
})();

but I recently came across one like this with the last two brackets inside the final one:

(function () {
    console.log("hi");
}());

I assumed it wouldn't work, but surprisingly it does. This, however, obviously doesn't:

function () {
    console.log("hi");
}();

Why is this? The two working versions seem to do the same thing, but is there a difference?

DrRelling
  • 122
  • 1
  • 4
  • 10

2 Answers2

0

You can find more from MDN.

It is a design pattern which is also known as Self-Executing Anonymous Function and contains two major parts. The first is the anonymous function with lexical scope enclosed within the Grouping Operator (). This prevents accessing variables within the IIFE idiom as well as polluting the global scope.

The second part is creating the immediately executing function expression (), through which the JavaScript engine will directly interpret the function.

So the first part answered your question, that you need a Grouping Operator() to prevent accessing variables within the IIFE idiom as well as polluting the global scope

Community
  • 1
  • 1
Isaac
  • 12,042
  • 16
  • 52
  • 116
0

Cause an IIFE only works with function expressions like:

(function() {})

Not with function statements.

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151