Gabriel Rufino
Gabriel Rufino's Blog

Gabriel Rufino's Blog

Reverse switch?

Reverse switch?

Gabriel Rufino's photo
Gabriel Rufino
·Apr 27, 2021·

1 min read

Subscribe to my newsletter and never miss my upcoming articles

Listen to this article

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!

 
Share this