The following evaluate to true
:
new Number(2) == 2
new String(\"2\") == \"2\"
Obviously, but so do the following:
What I think ==
is basically does value comparision.
In above all situations it's comparing just values. But in this one
new Number(2) == new String("2")
Both are objects so it doesn't compare values, it tries to compare values of object references. That's why it returns false
.
Just try:
new Number(2) == new Number(2)
that returns
false
and you will have the answer: there are 2 different objects that have 2 different references.
Because JavaScript has both primitive and object versions of numbers and strings (and booleans). new Number
and new String
create object versions, and when you use ==
with object references, you're comparing object references, not values.
new String(x)
and String(x)
are fundamentally different things (and that's true with Number
as well). With the new
operator, you're creating an object. Without the new
operator, you're doing type coercion — e.g. String(2)
gives you "2"
and Number("2")
gives you 2
.