This page looks best with JavaScript enabled

A Different IIFE Syntax

 ·   ·  ☕ 1 min read

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 -

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
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.

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things


What's on this Page