So This switch Statement Is Broken... Let’s Fix It

alphaxardalphaxard
2 min read

I was working on some JavaScript logic with a friend and wrote this:

let age = 18
switch (age) {
  case age < 13:
    console.log("child")
    break;
  case age<18:
    console.log("Teenager")
}

Oops. Didn’t work.

❓ So What’s the Problem?

Turns out that in JavaScript, switch uses strict equality (===). So:

The age is 18.

The expression age < 18 is evaluated before the switch statement runs, resulting in false.

So this is what the switch really sees:

let age = 26
switch (18) {
  case false:
    console.log("Child")
}
//That’s 18 === false, which… doesn’t compute 😅

🧠 The Fix — switch(true)

I wanted to clean up nested if...else blocks, and here’s the trick that finally made it click:

switch (true) {
  case age < 13:
    console.log("Child")
    break
  case age < 18:
    console.log("Teenager")
    break
  default:
    console.log("Adult")
}

Instead of comparing values, we flip the logic: "Which of these conditions is true?"

Here's what's really happening step-by-step:

let age = 26
switch (true) {
  case age < 13:// true ===false => false
    console.log("Child")
    break
  case age < 18: // true ===false => false
    console.log("Teenager")
    break
  default:
    console.log("Adult")
}

And boom—it works.

⚡ Use Cases( Price Tiers)

let spend = 2000
switch (true) {
  case spend > 1000:
    tier = "Gold"
    break
  case spend > 500:
    tier = "Silver"
    break
  default:
    tier = "Bronze"
}

🔍 Still Curious? MDN Has You Covered

Here's where you can learn the full rules of how switch statements and strict equality work in JavaScript.

💬 Got a better pattern? Drop your favorite switch() trick or use case in the comments!

1
Subscribe to my newsletter

Read articles from alphaxard directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

alphaxard
alphaxard