55

Is there a way to write a conditional switch statement in JavaScript?

I'm guessing not, since the following is always going to default:

var raw_value = 11.0;
switch(raw_value)
{
    case (raw_value > 10.0):
      height = 48;
      width = 36;
      break;
    case (raw_value > 5.0):
      height = 40;
      width = 30;
      break;
    default:
      height = 16;
      width = 12;
      break;
}

If not, what should I use instead - a long if/else statement?

3
  • One nice solution would be an array, and a JavaScript version of this recent PHP question.... but that's not going to be trivial to port. Commented Nov 2, 2010 at 21:24
  • It's not THAT long of an if - else statement (if, else if, else). Pretty standard (and less indentation). Commented Nov 2, 2010 at 21:26
  • If/else takes less space, easier to read, less to write and less prone to self inflicted bugs.. Commented Nov 2, 2010 at 22:10

5 Answers 5

161

Like this:

var raw_value = 11.0;
switch(true) {
    case (raw_value > 10.0):
      height = 48;
      width = 36;
      break;
    case (raw_value > 5.0):
      height = 40;
      width = 30;
      break;
    default:
      height = 16;
      width = 12;
}

The expressions in the case statements will evaluate to true or false, and if that matches the switch condition... voilà. The default acts like an else.

Bonus: you can invert the whole logic by simply replacing true with false. With if ... else if statements, you'd have to edit every if-clause individually.

Sign up to request clarification or add additional context in comments.

3 Comments

This should be the right answer, as it does what the OP asked in the style asked. However, I had a hard time the first time I saw a switch(true) statement.
Up voted and should be marked as the answer. Most programmers (or maybe just me) with server language exp. find the JS implementation non-intuitive. Its kind of weird starting the evaluated expression and working backwards!
Just a side note. This is a clear example to not assume the guy with the most SO points has the right answer.
36

In a switch statement, the evaluated value of the switch expression is compared the the evaluated values of the cases. So here the value of raw_value (number) is compared to raw_value > 10.0 (comparison expression) and raw_value > 5.0 (comparison expression).

So unless one of your case expressions yield a number equal to 11.0 or you use the switch expression true, you will always get the default case.

Just use a simple if/else instead:

var raw_value = 11.0;
if (raw_value > 10.0) {
    height = 48;
    width = 36;
} else if (raw_value > 5.0) {
    height = 40;
    width = 30;
} else {
    height = 16;
    width = 12;
}

1 Comment

And without the need for break, it's just as clean as the original.
1

No, the switch statement does not work used like that. However, this statement is not always simpler. For example, the switch version takes 15 lines:

var raw_value = 11.0;
switch(raw_value) {
    case (raw_value > 10.0):
      height = 48;
      width = 36;
      break;
    case (raw_value > 5.0):
      height = 40;
      width = 30;
      break;
    default:
      height = 16;
      width = 12;
      break;
}

and the "long" if/else version only 11:

var raw_value = 11.0;
if (raw_value > 10.0) {
      height = 48;
      width = 36;
} else if (raw_value > 5.0) {
      height = 40;
      width = 30;
} else {
      height = 16;
      width = 12;
}

So in your case, it is better to use the second one than the first...

2 Comments

Less lines of code is not objectively"better", since "good code" is subjective. Readability and ease of understanding are two other factors. I would perhaps add that this approach is better "if the goal is using as few lines of code as possible"
Based on how 'switch' is working, the first example will always hit default
1

Don't try this at home, or take it too seriously, this is just for sugary fun...

function conditionalSwitch(value, cond, callback /* cond, callback, cond, callback, ... */ ) {
  for (var i = 1; i < arguments.length; i += 2) {
    if (arguments[i](value)) {
      arguments[i + 1](value);
      return;
    }
  }
}



function test(val) {
  let width, height;

  conditionalSwitch(val,
  
    (val) => val > 10,
    () => [height, width] = [48,36],

    (val) => val > 5,
    () => [height, width] = [40, 30],

    // Default
    () => true,
    () => [height, width] = [16, 12]
  )
  console.log(width, height);
}


test(4.9);  // 12 16
test(5.1);  // 30 40
test(10.1); // 36 48

2 Comments

Erm, shouldn't this be in codepen or something, some place fun! Don't see the point of it being here...
@sij_a And thee years later, there it is :D
1

see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch

You can use switch (true) and add cases that evaluate to boolean

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.