IIFE: Pros & Cons

A few words to explain that technique

2018-06-01

In this article we spend some time to describe what is IIFE [ifi] and why each
Junior Developer should know this as quick as he can.

This is simple listing of JavaScript code:

1
2
3
4
5
6
7
8
9
(function () {
'use strict';

function foo() {
console.log('bar');
}

foo();
})();

You can see that the whole code is wrapped by a function in round brackets,
and immediately invoked with another pair of round brackets.

This syntax is called Immediately Invoke Function Expression - IIFE

Pros

  • function wraps some code which could define variable, so it is defines in
    a local scope
  • without any module definition variable define in global namespace,
    which is called anti-pattern

Cons

  • each wrap generates indentation
  • when project does not have any module

Comments: