Is it safe to assume strict comparison in a JavaScript switch statement?

JavascriptTypesComparisonType ConversionSwitch Statement

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

Take a look at http://www.ecma-international.org/ecma-262/5.1/#sec-12.11">ECMA 262, section 12.11, the second algorithm, 4.c.

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

Solution 2 - Javascript

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.

Solution 3 - Javascript

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

Source: switch - JavaScript | MDN

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPaulView Question on Stackoverflow
Solution 1 - JavascriptFederico LebrónView Answer on Stackoverflow
Solution 2 - JavascriptHalcyonView Answer on Stackoverflow
Solution 3 - Javascriptma11hew28View Answer on Stackoverflow