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?
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.
= 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.
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.
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 === .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With