Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem with javascript switch statement


elmid = "R125";

switch(true){

    case elmid.match(/R125/):
      idType = "reply";
    break;

}

alert(idType);  // Returns undefined

-------------------BUT----------------------

elmid = "R125";

if (elmid.match(/R125/)){idType = "reply";}

alert(idType);  // Returns "reply"


Using the swtich returns undefined but using an if returns the expected value, what is causeing the switch to fail ? Why is this the case? what am i doing wrong here? can any one explain why I get different results =).

NOTE: No advices to use an if statement in this case I know that, my question concise for asking there hence there is not only 1 case in the switch statement.

like image 752
Abdullah Khan Avatar asked Aug 16 '10 06:08

Abdullah Khan


1 Answers

elmid.match(/R125/)

This returns the actual regex matches, not true or false.

When you're writing an if statement and using ==, some basic type conversion can be performed so that it works as expected. Switch statements use the identity comparison (===), and so this won't work.

If you want to do it this way, use regex.test() (which returns a boolean) instead.

case /R125/.test(elmid):
like image 75
Anon. Avatar answered Sep 22 '22 15:09

Anon.