Arc Forumnew | comments | leaders | submitlogin
1 point by thaddeus 5114 days ago | link | parent

a reply for one layer down:

> JavaScript allows arbitrary expressions in switch statements

That's right... looks like it was the test data I was thinking of, which isn't entirely relevant, given you can accomplish the same thing in the end.

> Why make the common case difficult?

A fall-through could be nicer than many breaks. Trying to think of all the scenarios required to make this usable, i.e., do you need a break to get out of a fall-through? Maybe that's why they just went with break. either way, it's a good idea.



1 point by Pauan 5114 days ago | link

The current behavior for switch is simple: it will continue until it finds a break statement. Thus:

  switch (true) {
  case true:
      console.log(1);
  case true:
      console.log(2);
  case true:
      console.log(3);
      break;
  case true:
      console.log(4);
  }
...which outputs 1, 2, and 3. If you wanted to have the same behavior using the continue statement, you would use this:

  switch (true) {
  case true:
      console.log(1);
      continue;
  case true:
      console.log(2);
      continue;
  case true:
      console.log(3);
  case true:
      console.log(4);
  }
As far as I know, this would have exactly the same power as using break; but would be much better suited for the very common case of not wanting fallthru. I think it's much more readable, too: makes it very obvious where it falls through. And it's less error prone... no more strange bugs if you accidentally forget to add in a break; statement.

In fact, in my years and years of programming in JavaScript, I have used if/else blocks many many times (some of which could have been switch statements), and only wanted fallthru a handful of times. I think allowing fallthru is fine, but it should be made explicit, rather than implicit.

The only possible argument I can think of in favor of implicit fallthru is using a switch inside a `for` loop:

  for (var i = 0; i < array.length; i += 1) {
      switch (array[i]) {
      case "foo":
          continue;
      }
  }
...but that's actually ridiculous because I'm fairly sure that breaking out of a loop is far more common than continuing. In which case explicit fallthru would be better with loops.

-----