0

In an attempt to better understand switch, I have been playing with the following JS code:

switch(true) {
  case false: console.log("1"); break;
  case false: console.log("2"); break;
  case true : console.log("Unconditional");
  case false: console.log("4"); break;
  case false: console.log("5"); break;
  default: console.log("Default");    
}

My output is simply:

Unconditional
4

I'm surprised that the "4" line executed since the relevant case expression was, "false". Similarily, I'm also surprised that the "Default" line didn't execute. (In a similar test with all breaks removed, the Default line did execute.) Can someone please explain what's going on? Thanks.

user3311045
  • 689
  • 1
  • 7
  • 15
  • You didn't break after the `case true`, so it goes on to the next case. The default doesn't run because one of the cases was fulfilled. – CertainPerformance Aug 08 '22 at 18:22
  • I know you're only experimenting but this isn't a very good use-case for `switch`. [The documentation might be of some use](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch). – Andy Aug 08 '22 at 18:40

0 Answers0