0
switch(type)
{
    case 'home':
         console.log('home switch');
         break;
}

The above code does not write out to the console, neither does the following:

switch(type)
{
     case "home":
         console.log('home switch');
         break;
}

The following, however, does:

if (type == 'home')
{
     console.log('home if');
}

I don't have a clue why. This isn't a show-stopper, I can use the if statement instead, but I'm genuinely curious as to why this is the case.

NOTE: These statements are a straight replace, nothing else to consider here. No change in scope, no code I'm not mentioning that could be interfering with the value of type.

1 Answers1

8

That's not the equivalent if-statement. The switch statement is specified to use the strict equality === operator.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • I didn't realize this. I've just changed my `if` to use `===` and, as you'd expect, it hasn't met the condition. I don't really understand what's happened here though, it's merely a string - surely `===` would be satisfied? If not, how else do you switch case a string? –  May 02 '14 at 14:14
  • @DeeMac: Looks like it's not then. Please make a demo with an example value for `type`. Also test `console.log(typeof type)`. – Bergi May 02 '14 at 14:15
  • 1
    This is not a solution to OP question but i learned something today! – laaposto May 02 '14 at 14:16
  • You might try `switch(String(type)) { … }` then. – Bergi May 02 '14 at 14:17
  • @laaposto: Until the OP shows more of his code, I cannot offer a "solution". It does answer the question "*I don't have a clue why*" though :-) – Bergi May 02 '14 at 14:19