Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In JavaScript, why don't any objects equal each other, except strings? [duplicate]

Everything in JS is an object. I've always known that, and I totally understand that. I know why {} !== {}. It's two different objects. Same as if you were to write out new Object() == new Object().

Some other examples:

{} == {} // => false
[] == [] // => false
/ / == / / // => false
new String() == new String() // => false

But, Strings are objects too (it's why you can do ''.replace() and extend them), so why does this work:

'' == '' // => true

Obviously it'd be a huge headache to compare two strings if this didn't work, but this seems inconsistent with the rest of the language. Internally, what's going on? Is it just a one-off or is there some other concept behind this?

like image 211
Oscar Godson Avatar asked May 21 '13 23:05

Oscar Godson


People also ask

Why objects are not equal in JS?

In JavaScript, objects are a reference type. Two distinct objects are never equal, even if they have the same properties. Only comparing the same object reference with itself yields true. For more information about comparison operators, see Comparison operators.

Why does JavaScript use === instead of ==?

= Vs == VS === in JavaScript== in JavaScript is used for comparing two variables, but it ignores the datatype of variable. === is used for comparing two variables, but this operator also checks datatype and compares two values. Checks the equality of two operands without considering their type.

Why does comparing two JavaScript objects always return false?

Comparing two objects like this results in false even if they have the same data. It is because those are two different object instances, they are referring to two different objects. There is no direct method in javascript to check whether two objects have the same data or not.

Are objects equal JavaScript?

Even if two object has same key and value pair it will return false. As you can see above example, both name and fullName are identical. Yet, the object are not equal either with == or === .


1 Answers

JavaScript basically treats strings and numbers as scalars at all times, converting them to objects when a method is called, and converting back afterward, in cases where you aren't explicitly declaring new String("");

Same with numbers.

Without string/number/boolean equality, you'd have a hard time doing much of anything.

like image 98
Norguard Avatar answered Oct 21 '22 03:10

Norguard