I have the following switch block:
var str = 'matches[pw1]';
switch (str)
{
case (str.indexOf('matches') > -1) :
console.log('yes');
break;
default:
console.log(str.indexOf('matches') ) ;
console.log('no');
break;
}
What I want is, that if str contains the word ‘matches’, then it should run the first case block, otherwise the default block.
However when I run this, the output I get is ‘0’, and then ‘no’, meaning the default block is running despite the conditions for the first case being met.
Any ideas what’s wrong?
You cannot do that with a switch statement. A switch statement compares the result of evaluating the switch expression (in this case
str) with the values of the case labels. The case labels can be expressions (as in your example), but if they are the expressions are evaluated and then compared against the value above using===. (That’s what the ECMAScript 5.1 spec says …)So what your code is actually doing for that case is (roughly speaking):
(str.indexOf('matches') > -1)which gives youtrueorfalsetrueorfalsewith the value ofstr… which fails and the case body isn’t executed.Now I think you could make your approach work as follows:
but that stinks from a code readability perspective (IMO).