When getting a value conditionally, I like to use the ternary operator (?:
) so that I can have const
variable declarations:
// Better
const foo = x ? 'bar' : 'goo';
// Worse
var foo;
if (x) {
foo = 'bar';
} else {
foo = 'goo';
}
I would like to do the same for switch
statements. I can use a series of nested ?:
, but this is quite cumbersome and does not scale well:
const foo = x === 1 ? 'bar' : (x === 2 ? 'goo' : 'zoo');
I could even use a closure, but this is also verbose:
const foo = (() => {
switch(x) {
case 1:
return 'bar';
case 2:
return 'goo';
default:
return 'zoo';
}
})();
Is there a switch
expression in JavaScript?
You should first and foremost keep things readable and manageable. Squeezing two or three conditions with four or five values into one line is unreadable almost any way you turn it.
I'd suggest this very declarative approach:
let fooToBarMap = {
foo: 'bar',
baz: 42
};
let y = fooToBarMap[x] || 'default';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With