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?
The value null represents the absence of any object, while the empty string is an object of type String with zero characters.
An empty string is a string instance of zero length, whereas a null string has no value at all. An empty string is represented as "" . It is a character sequence of zero characters. A null string is represented by null .
Truthy or Falsy When javascript is expecting a boolean and it's given something else, it decides whether the something else is “truthy” or “falsy”. An empty string ( '' ), the number 0 , null , NaN , a boolean false , and undefined variables are all “falsy”. Everything else is “truthy”.
In JavaScript “0” is equal to false because “0” is of type string but when it tested for equality the automatic type conversion of JavaScript comes into effect and converts the “0” to its numeric value which is 0 and as we know 0 represents false value. So, “0” equals to false.
Quoting the doc (MDN):
Equal (==)
If the two operands are not of the same type, JavaScript converts the operands then applies strict comparison. If either operand is a number or a boolean, the operands are converted to numbers if possible; else if either operand is a string, the other operand is converted to a string if possible.
As a
operand type here is Number
, b
gets converted to Number as well. And Number('')
evaluates to 0
.
This can be quite surprising sometimes. Consider this, for example:
console.log(0 == '0'); // true console.log(0 == ''); // true console.log('' == '0'); // O'RLY?
... or this:
console.log(false == undefined); // false console.log(false == null); // false console.log(null == undefined); // fal.... NO WAIT!
...and that's exactly why it's almost always recommended to use ===
(strict equality) operator instead.
0
, ""
(Empty String), false
all technically have the same value, when typecasted. If you need to strictly treat them, you can use ===
.
It is the same with similar programming languages, like PHP.
var a = 0; var b = ''; //empty string if(a == b){ console.log('equal'); //this is printed in console }else{ console.log('not equal'); }
if(a === b){ console.log('equal'); }else{ console.log('not equal'); //this is printed in console }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With