Switch over class types in JavaScript

Switching over a set of class types is a useful pattern. In JavaScript, one way to implement this pattern is to use the constructor property of an object instance.

Say we have hierarchy of a base class Shovel and two child classes: SnowShovel and Trowl.

class Shovel {}

class SnowShovel extends Shovel {}
class Trowel extends Shovel {}

In a switch statement, we can check what type of shovel we have by using the constructor property:

let myShovel = new SnowShovel();

switch(myShovel.constructor) {
case SnowShovel:
console.log("Must be winter!");
break;
case Trowel:
console.log("Must be gardening season!");
break;
default:
console.log("Never seen that type of shovel before");
}

// logs "Must be winter!"

This works because the constructor property references the function that created the object instance. So, in our switch cases, we can reference those functions directly. Read more about the property on MDN.