Skip to main content

Reverse switch?

Published 1 min readMarkdown
Reverse switch?

I recently saw something that caught my attention and I called it Reverse Switch. Probably there's a better name.

A conditional switch where the expression takes boolean constants (true or false) and the switch cases take expressions.

Some like this:

switch (true) {
  case isEven(x):
    console.log('x is even!')
    break
  case isPrime(x):
    console.log('x is prime!')
    break
  case x > 10:
    console.log('x is greater than 10')
    break
  default:
    console.log('x is not even, is not prime and is not greater than 10')
}

My head exploded because I never thought about it. I always did it as follows:

if (isEven(x)) {
  console.log('x is even!')
} else if (isPrime(x)) {
  console.log('x is prime!')
} else if (x > 10) {
  console.log('x is greater than 10')
} else {
  console.log('x is not even, is not prime and is not greater than 10')
}

And here comes my question:

  1. Have you seen or done something like that?
  2. Do you think it is good practice?
  3. Which one is more readable?

Let's talk about it!

No comments yet. Be the first to comment.

More from this blog