0

If the result of this code illustrates that the switch-case implies strict equality checking..

//code 1

switch(0)
{
case false: alert('NOT strict');
break;
case 0: alert('strict');    // shows up as expected
}

..then why does the result of the second one seem to tell the opposite?.. Did any type conversion occur or something?

// code 2

switch(0)
{
case 0: alert('may or may not be strict');    // I just added this case.. does it have an effect.. why?
case false: alert('NOT strict');    // this shows up!..
break;
case 0: alert('strict');    // ..instead of this!
}

note 1: My question here is not whether strict equality checking occurs or not.. I already looked up that question's answer here. My question is.. why that contradiction between the two results? Shouldn't code 2 give us 'strict' instead of 'NOT strict'?

Trachyte
  • 373
  • 1
  • 4
  • 8
  • Possible duplicate of [Why is Break needed when using Switch?](https://stackoverflow.com/questions/39757797/why-is-break-needed-when-using-switch) – John Montgomery Dec 05 '18 at 19:56
  • Although they are related.. this question is not a a duplicate of that one.. simply because.. I had no idea that the issue has to do with leaving the break statement.. and that's why I haven't even mentioned it.. but.. once I learned that the issue actually has to do with leaving the break statement.. the question you mentioned is the next logical one.. and that's why they are related.. not duplicated. – Trachyte Dec 06 '18 at 18:13

2 Answers2

0

In your second version you left out break at the end of the first case 0:. So it continues with the next case without performing its test. Then the break statement prevents it from executing the second case 0:.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • "without performing its test".. why?! – Trachyte Dec 06 '18 at 19:41
  • Because that's the way `switch/case` works. It looks for the first `case` that matches the value, then starts executing code from there until it gets to `break`. – Barmar Dec 06 '18 at 20:14
  • This allows you to write something like `switch($answer) { case 'y': case 'yes': ...; break; case 'n': case 'no': ...; break }` – Barmar Dec 06 '18 at 20:15
0

You have no break statement, so the execution falls-through. It's no different than this:

switch(0)
{
case 0:
  alert('case 0');
  // no break statement, so the next case runs if this one did
case 'bologna':
  alert('case bologna');
}
Paul
  • 139,544
  • 27
  • 275
  • 264