Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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")
like image 521
jaypeagi Avatar asked Aug 28 '14 15:08

jaypeagi


People also ask

What does != Mean in JavaScript?

The inequality operator ( != ) checks whether its two operands are not equal, returning a Boolean result. Unlike the strict inequality operator, it attempts to convert and compare operands that are of different types.

What is new string in JavaScript?

The String constructor is used to create a new String object. When called instead as a function, it performs type conversion to a primitive string, which is usually more useful.

How do you check if string is a number JavaScript?

To check if a string contains numbers in JavaScript, call the test() method on this regex: /\d/ . test() will return true if the string contains numbers. Otherwise, it will return false . The RegExp test() method searches for a match between a regular expression and a string.

How do I convert a string to a number?

You convert a string to a number by calling the Parse or TryParse method found on numeric types ( int , long , double , and so on), or by using methods in the System. Convert class. It's slightly more efficient and straightforward to call a TryParse method (for example, int.


2 Answers

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.

like image 199
T.J. Crowder Avatar answered Sep 29 '22 09:09

T.J. Crowder


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.

like image 37
Mritunjay Avatar answered Sep 29 '22 09:09

Mritunjay