121

I have a variable that can either be boolean false, or an integer (including 0). I want to put it in a switch statement like:

switch(my_var){
    case 0:
         // Do something
         break;
    case 1:
         // Do something else
         break;
    case false:
         // Some other code
}

In my tests in Google Chrome, it seems to work perfectly, but I'm a little nervous to use it because I'm afraid that in some browsers, if my_var is false, it might execute the first case since 0 == false.

I'm just wondering if there is anything official in JavaScript that says the switch statement will use strict comparison such that 0 !== false, but I can't find anything myself, and I'm not sure if this will work well in different JavaScript engines. Does anybody know if the comparison done by a switch statement is guaranteed to be strict?

Pang
  • 9,564
  • 146
  • 81
  • 122
Paul
  • 139,544
  • 27
  • 275
  • 264

3 Answers3

118

Take a look at ECMA 262, section 12.11, the second algorithm, 4.c.

c. If input is equal to clauseSelector as defined by the === operator, then...

luiges90
  • 4,493
  • 2
  • 28
  • 43
Federico Lebrón
  • 1,772
  • 1
  • 11
  • 10
  • 11
    It's been [partying like that since 1999](http://www.ecma-international.org/publications/files/ECMA-ST-ARCH/ECMA-262,%203rd%20edition,%20December%201999.pdf) (page 68, s. 12.11, CaseBlock #3) – Walf Nov 18 '16 at 05:46
  • 2
    Then... what? I'm not sure why you cut off the quote here. – Oleg V. Volkov Jul 17 '20 at 15:06
  • 2
    That section looks like a bunch of gibberish; the other answers are a lot more helpful. I wonder why incomprehensible things like that get so many upvotes. – nCardot Aug 15 '21 at 02:39
43

http://qfox.nl/notes/110 answers your question. (This guy knows a lot about the nitty gritty of JavaScript)

Switches in Javascript use strict type checking (===). So you never have to worry about coercion, which prevents a few wtfjs :). If on the other hand you were counting on coercion, tough luck because you can't force it.

Halcyon
  • 57,230
  • 10
  • 89
  • 128
  • https://jsfiddle.net/to469fLm/4/ , you could generalize the coercing function to achieve your needs – darethas Mar 11 '16 at 17:13
10

Yes, switch "[uses] the strict comparison, ===".

Source: switch - JavaScript | MDN

ma11hew28
  • 121,420
  • 116
  • 450
  • 651