Possible Duplicate:
Implied string comparison, 0='', but 1='1'
Executing the following case in javascript, I get 0 equal to ” (an empty string)
var a = 0;
var b = '';//empty string
if(a==b){
console.log('equal');//this is printed in console
}else{
console.log('not equal');
}
Could anyone guide that what is the reason behind this?
Quoting the doc (MDN):
As
aoperand type here isNumber,bgets converted to Number as well. AndNumber('')evaluates to0.This can be quite surprising sometimes. Consider this, for example:
… or this:
…and that’s exactly why it’s almost always recommended to use
===(strict equality) operator instead.