Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is [] !== [] in JavaScript? [duplicate]

Why is [] !== [] in JavaScript?

I read through https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness but I could not find anything that explains this.

Edit: I don't think this question or this question is an exact duplicate of mine. It asks about the == operator which just behaves crazy. The answer is an answer to my question but it's not the same question.

like image 477
fahrradflucht Avatar asked Oct 28 '16 21:10

fahrradflucht


People also ask

Why [] == [] is false in JavaScript?

The reason for [] == false even though [] is truthy is: the comparison [] == false compares the value of [] to false . And to get the value of [] , the JavaScript engine first calls [].

What does mean [] in JavaScript?

It is shorthand for empty array. Same as new Array(). Also {} is an empty object. Objects are like hashtables in Js so you can use it as a dictionary. Copy link CC BY-SA 2.5.

What is the difference between [] and {} in JavaScript?

{} is shorthand for creating an empty object. You can consider this as the base for other object types. Object provides the last link in the prototype chain that can be used by all other objects, such as an Array . [] is shorthand for creating an empty array.

How do you remove duplicates from array of objects in JS?

To remove the duplicates from an array of objects:Use the Array. filter() method to filter the array of objects. Only include objects with unique IDs in the new array.


3 Answers

That does a reference check on the two array literals to see if they are the same instance. The fact that you have two literals means that you are constructing two separate arrays, therefore the reference check returns false. This would return true:

var a = []
var b = a

//b === a

This is because we have two references to the same array.

like image 197
Lew Avatar answered Oct 07 '22 13:10

Lew


Because [] is an object, and a comparison of objects only returns true when both sides of the comparison point to the exact same object. You have created two separate objects, so they aren't equal.

var x = []
var y = x
var z = []

x == x // true
x == y // true
x == z // false
like image 27
Mogzol Avatar answered Oct 07 '22 15:10

Mogzol


[] creates a new (and empty) array each time you write it. You are comparing two arrays, regardless of their content, their pointer (or reference) are being compared.

var array = [];
var anotherArray = array; // these two will point to the same array, so they are equal


array === anotherArray; // true
array === []; // false


array.push('something');
anotherArray.length; // 1
like image 42
Aᴍɪʀ Avatar answered Oct 07 '22 14:10

Aᴍɪʀ