jaypeagi
jaypeagi

Reputation: 3141

Why does new Number(2) != new String("2") in JavaScript

The following evaluate to true:

new Number(2) == 2
new String("2") == "2"

Obviously, but so do the following:

"2" == 2
new Number(2) == "2"
new String("2") == 2

So can someone explain clearly why he following evaluates false?

new Number(2) == new String("2")

Upvotes: 6

Views: 120

Answers (3)

ROMANIA_engineer
ROMANIA_engineer

Reputation: 56694

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.

Upvotes: 1

Mritunjay
Mritunjay

Reputation: 25892

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.

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1074989

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.

Upvotes: 6

Related Questions