Why switch and if statement in Javascript treat boolean different, confused -
i've got switch , if problem in javascript, code following.
var a=0; if(a){ console.log("a true"); } else if(!a) { console.log("a false"); } else { console.log("a not true or false"); } switch(a){ case true: console.log("switch... true"); break; case false: console.log("switch... false"); break; default: console.log("switch... not true or false"); }
when ran code above, got result in console confused me lot:
a false switch... not true or false
i think should this:
a false switch... false
anyone knows why happens? appreciate answers.
if (!0) evalutes true. there rule non 0 in if evaluate true vie versa.
but switch 0 explicitly checked against case values , 0 neither true or false , hence default statement gets executed.
Comments
Post a Comment