Why is the new number (2)! = New String ("2") in JavaScript

The following evaluates to true :

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

Obviously, but do the following:

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

So can someone explain why it evaluates to false ?

 new Number(2) == new String("2") 
+6
source share
3 answers

Because JavaScript has both primitive and object versions of numbers and strings (and logical values). new Number and new String create object versions, and when you use == with object references, you compare object references, not values.

new String(x) and String(x) are fundamentally different things (and this is true with Number ). Using the new operator, you create an object. Without the new operator, you are executing a coercion type โ€” for example, String(2) gives you "2" and Number("2") gives you 2 .

+6
source

What I think == basically does a comparison of values.

In the above situations, it only compares the values. But in this

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

Both are objects; therefore, they do not compare values; it tries to compare the values โ€‹โ€‹of object references. That is why it returns false .

+1
source

Just try:

 new Number(2) == new Number(2) 

which returns

falsely

and you will have the answer: there are two different objects that have two different links.

+1
source

Source: https://habr.com/ru/post/974500/


All Articles