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
orfalse
) 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:
- Have you seen or done something like that?
- Do you think it is good practice?
- Which one is more readable?
Let's talk about it!