Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is 0 == "" true in JavaScript

Tags:

javascript

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.

like image 487
Horst Walter Avatar asked Sep 30 '11 01:09

Horst Walter


People also ask

Why is false == 0 is true in JS?

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.

Why is 0 as a string true?

"0" is a string, and since it's not empty, it's evaluated to true.

Does 0 evaluate to true in JavaScript?

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 .

Why == is false in JavaScript?

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.


1 Answers

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

like image 87
Šime Vidas Avatar answered Oct 12 '22 04:10

Šime Vidas