In SQL and PL/SQL we can have a CASE expression like this:
y := case x
when 1 then 'foo'
when 5 then 'bar'
when 7 then 'baz'
else 'wak'
end;
The simplest expression of this type I can think of in javascript is to use nested ternary operators, like this:
y = (x==1)
? "foo"
:( (x==5)
? "bar"
:( (x==7)
? "baz"
: "wak"
)))
Is there a simpler/clearer way to form this sort of thing as an expression?
NOTE: I know about the switch statement, but here I'm looking for an expression.
you can use a key-value map
y = {1: "foo", 5: "bar", 7: "then"}[x] || "wak";
or if the map is bigger or you use falsy values, ...
var map = {
1: "foo",
5: "bar",
7: "then"
};
y = x in map? map[x]: "wak";
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