Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why {} == {} is false in JavaScript [duplicate]

Tags:

javascript

Why {} == {} and {} === {} is false in javascript?

{} == {} // false
{} === {} // false
like image 566
rel1x Avatar asked Feb 19 '15 06:02

rel1x


People also ask

Why is {} === {} false in JavaScript?

Each object, each {} is distinct. Same applies to arrays, too. Show activity on this post. 2) it does not make any difference whether you use == or === for comparing objects, because comparing them always returns false.

Why does it return false when comparing two similar objects in JavaScript?

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.

What does {} mean in JavaScript?

google doesn't have value (undefined, null) then use {} . It is a way of assigning a default value to a variable in JavaScript. Follow this answer to receive notifications.

Why in JS [] == this is true?

Double equals, == , performs an amount of type coercion on values before attempting to check for equality. So arr == arr returns true as you'd expect as what you are actually checking is if [] == [] and both sides of the equation are of the same type.


2 Answers

javascript compares objects by identity, not value. Each object, each {} is distinct.

Same applies to arrays, too.

like image 126
Andras Avatar answered Oct 19 '22 18:10

Andras


1) The reason for this is that internally JavaScript actually has two different approaches for testing equality. Primitives like strings and numbers are compared by their value, while objects like arrays, dates, and plain objects are compared by their reference. That comparison by reference basically checks to see if the objects given refer to the same location in memory.so

{} == {}   is false

2) it does not make any difference whether you use == or === for comparing objects, because comparing them always returns false.

like image 8
BIdesi Avatar answered Oct 19 '22 19:10

BIdesi