0

This is because the equality operator == does type coercion, meaning that the interpreter implicitly tries to convert the values before comparing.

Looked into this

but, 0 == '' , I dont understand why it returns true. Can any one explain? what is 0 converted to ? and what is '' converted to to return true ?

asked May 6, 2014 at 20:54
2

1 Answer 1

3

When abstractly comparing a string and a number, regardless of the order, the string will be converted ToNumber() for the comparison:

4. If Type(x) is Number and Type(y) is String,
 return the result of the comparison x == ToNumber(y).
5. If Type(x) is String and Type(y) is Number,
 return the result of the comparison ToNumber(x) == y.

In the case of 0 == "", ToNumber("") results in 0, which is exactly the other value:

0 == "" // becomes...
0 == 0 // becomes...
true

Note: You can see how the internal-onlyToNumber() handles different values by using the Number() constructor without new:

console.log(Number(""))
// 0
answered May 6, 2014 at 20:59
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.