A Different IIFE Syntax

Here’s a different syntax for our favourite IIFE’s.

Immediately invoked function expressions enable us to write functions without using “functions”. Well - just kidding. They are functions but with a different syntax.

A typical IIFE looks like this -

const x = 1,
  y = 9;
var sum = 0;
(function() {
  sum = x + y;
  console.log("sum: ", sum);
}();

/* output
sum:  10
*/

There is another interesting syntax that is lesser known. At least it was not known at all to me-self until I came across the syntax in some library.

const x = 1,
  y = 9;
var sum = 0;

// prettier-ignore
!function() {
  sum = x + y;
  console.log("sum: ", sum);
// prettier-ignore
}();

/* output
sum:  10
*/

This syntax just makes use of the fact that the function is an object and so on and so forth.

As you might have second-guessed by the ‘prettier-ignore’ statements, this is not liked by Prettier. And, what is not liked by Prettier seems so unnatural.

comments powered by Disqus