Invoking Immediately-Invoked Function Expression (IIFE) with unary operators

Question | Dec 30, 2015 | hkumar 

An Immediately-Invoked Function Expression (IIFE) is a Javascript pattern that invokes an anonymous function at declaration. This pattern is used to create closures in a loop, create private members for modules, and initialization routines for frameworks or libraries to avoid cluttering variable namespace. Here we are going to talk about how IIFE's are invoked. If you want to learn more about practical usage of IIFE you can read here.

Here is the most commonly used way to write an IIFE:

(function () { console.log('Hello'); })();

Note the use of parentheses around function declaration. Those parantheses tell Javascript compiler to convert that function declration to function expression. And the following pair of parentheses invokes that function expression.

Enclosing the function in parantheses is not the only way to create a function expression. Another commonly spotted way to create function expression is using unary plus operator:

+function () { console.log('Hello'); }();  

Really? Yes, as a matter of fact you could use any unary operator - '!', '-', '~' - to create function expression. All of the following would have same desired result:

(function () { console.log('Hello'); })();
+function () { console.log('Hello'); }();
-function () { console.log('Hello'); }();
!function () { console.log('Hello'); }();
~function () { console.log('Hello'); }();

Work on following question on IIFE to gain more insight:

var module = {};
+function(mod,e) {

  var exponent = e; // private member

  mod.power = function(x) {
     return Math.pow(x, exponent || 1);
  };

}(module);

console.log(module.power(10));

What would be logged on console?