Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript equivalent of CASE expression

Tags:

javascript

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.

like image 630
Jeffrey Kemp Avatar asked Sep 27 '26 21:09

Jeffrey Kemp


1 Answers

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";
like image 145
Thomas Avatar answered Sep 30 '26 12:09

Thomas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!