Why is 0 == ""
true in JavaScript? I have found a similar post here, but why is a number 0 similar an empty string? Of course, 0 === ""
is false.
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.
"0" is a string, and since it's not empty, it's evaluated to true.
In JavaScript, a truthy value is a value that is considered true when encountered in a Boolean context. All values are truthy unless they are defined as falsy. That is, all values are truthy except false , 0 , -0 , 0n , "" , null , undefined , and NaN .
Javascript is like Java in that the == operator compares the values of primitive types, but the references of objects. You're creating two arrays, and the == operator is telling you that they do not point to the same exact object in memory: var b = new Array( 1, 2, 3 ); var c = new Array( 1, 2, 3 ); console.
0 == ''
The left operand is of the type Number.
The right operand is of the type String.
In this case, the right operand is coerced to the type Number:
0 == Number('')
which results in
0 == 0
From the Abstract Equality Comparison Algorithm (number 4):
If Type(x) is Number and Type(y) is String, return the result of the comparison x == ToNumber(y).
Source: http://es5.github.com/#x11.9.3
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