Zooly
Zooly

Reputation: 4787

How to use type–converting comparison instead of strict in switch Javascript?

Is there a way in Javascript to use the non-strict comparison in a switch statement ?

Example:

if (item == '3') { ... }
else if (item == 'Chocolate') { ... }
else { ... }

In a switch:

switch (item){
    case '3':
        ... break;
    case 'Chocolate':
        ... break;
    default:
        ...
}

I would like to test if item equals 3 (number) or '3' (char) in one case. I would like to avoid to write two cases for the same instructions.

Is it possible ?

Upvotes: 0

Views: 168

Answers (2)

Boris
Boris

Reputation: 1191

switch(item.toString()){
   case "3" :
       [...]

will behave as you want. it is a little hacky but it works.

As seen in comments below, there are many caveats to this however. It will work exactly as intended if you are sure that item is always a string or number.

booleans will be, well "true" or "false", and as such not fall into "0" and "1" cases.

objects, unless you have changed their toString method, will fall in a "[object Object]" case.

Arrays of one element will "toString" into the same case as their only elements.

I'll reiterate that you're probably way safer with using fall-through.

With that said... let's go into whacky territory

I've tried to override Object.prototype.valueOf as can be seen in fake-operator-overloading. the switch statement, however, doesn't call valueOf, so that's off the table. Now if you REALLY want the switch semantics AND an ==, you can do this :

switch(true){
    case key == 1 :
        //...
        break;
    case key == "something" :
        //...
        break;
    case key == false :
        //...
        break;
    default :
}

this method taken from mozilla doc

Now, to me that seems very complex for not a lot of bonus. but here you have it. I'm not even sure what case would some values such as {} or NaN fall into, but for example "" and 0 would go into falseprovided nothing catches them before

Upvotes: 4

Mohit Bhardwaj
Mohit Bhardwaj

Reputation: 10093

You can do it like this (It's called fall-through):

switch (item){
    case '3':
    case 3:
        ... break;
    case 'Chocolate':
        ... break;
    default:
        ...
}

Upvotes: 1

Related Questions