JSworkingevergreen

Switch vs Lookup

Pick the right shape.

Long if/else if chains comparing one value against a fixed set of cases are a smell. switch is one fix β€” but a plain object lookup is often even better.

The performance myth

Modern JS engines optimise both switch and if/else aggressively. The "switch is faster" claim is largely folklore β€” pick whichever reads better.

Fall-through is a footgun

Forgetting break is one of the oldest bugs in C-family languages. Modern linters (Biome, ESLint no-fallthrough) catch it.

When to use a lookup table

If every branch maps a value to another value (or to a single function call), an object or Map is shorter, easier to extend, and trivially serialisable.

When switch still wins

TypeScript discriminated unions get exhaustiveness checking when you switch on the discriminant β€” add default: const _: never = x and the compiler warns when a new variant goes unhandled.

Two more shapes worth knowing

A dispatch table also collapses a whole switch over an operation name into one indexed call β€” and when the keys aren't safe property names (or you want real key/value iteration), a Map plus an explicit default reads cleaner than obj[key] ?? fallback.

Try it 5 examples

The classic switch

JSintro
Press Run to execute

'February' hits its case and returns Second; 'July' matches no case so the default arm returns Other β€” the baseline shape every later example replaces with a lookup.