What would a Immediately Invoked Class Expression in JavaScript look like. This is the question I asked myself. I couldn’t find anything online, so I created one.

Below we have a Immediately Invoked Class Expression. This could also be called a Self-Executing Anonymous Class.

void new class {
  constructor () {
    statements
  }
}

We have all heard of the Immediately Invoked Function Expression (IIFE) it is also known as a Self-Executing Anonymous Function. I was curious how this would look with Classes. There are two parts of a IIFE. 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 creates the immediately executing function expression () through which the JavaScript engine will directly interpret the function.

To replicate this, our Immediately Invoked Class Expression would need at least these two features.

Above is what a Immediately Invoked Class Expression looks like. There are a few parts to this design pattern. Let me take you through them.

The void operator evaluates the given expression and then returns undefined. This will prevent our class polluting the global scope by always returning undefined.

The new operator interprets the defined anonymous class immediately. This then calls the classes constructor function as per the ECMAscript spec. So there you have it.