0

In javascript,for the Array, why does:

console.log([1] == [1])

return false?

Is there any auto type-change in it? And [1] === [1] return false too?

AndrewL64
  • 15,794
  • 8
  • 47
  • 79
sinbar
  • 933
  • 2
  • 7
  • 25

5 Answers5

2

Because two separate objects are never == (or ===) to one another, even if they are equivalent (have the same properties with the same values). Arrays are objects.

To compare arrays, see this question's answers.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

Because you are comparing two Array objects.

If you want to compare the values of the arrays you can do :

console.log([1] == [1]);

console.log(compareTwoArray([1], [1]));

console.log(compareTwoArray([1], [2]));

function compareTwoArray(arr1, arr2) {
  return arr1.length === arr2.length && arr1.every(x => arr2.includes(x));
}

Picture that you have a car, and your neighbour have the exact same car model.

enter image description here

If you want to strictly compare the cars, can you just look at the model? No, you will have to look at every part of the car (engine, wheels...) in order to say that they are "the same".

They are not one entity, this is two separated car, but to you, theirs characteristics make them identical.

So [1] is an array, and [1] and other array. But you would say they are identical if you look at theirs values.

Orelsanpls
  • 22,456
  • 6
  • 42
  • 69
0

In Javascript, Arrays are objects

typeof [1] // object

Which means when you write [1] you're creating a new object. Since the objects aren't the same object, you can't test their equality with == or ===.

See https://gomakethings.com/checking-if-two-arrays-are-equal/ for some ways to check array equality.

Jordan
  • 3,813
  • 4
  • 24
  • 33
0

Comparing two objects even if they are identical to each other will return false regardless of whether you use == or ===

For comparing two objects use JSON.stringify(object)

conole.log(JSON.stringify([1])==JSON.stringify([1]))

This will return true

If you want multiple comparisons you can set JSON.stringify to a variable :

let i = JSON.stringify

then you like this :

let i = JSON.stringify 
conole.log(i([1]) == i([1]))
conole.log(i([1]) === i([1]))
Muhammad Salman
  • 433
  • 6
  • 18
0

Objects (Array are object) are not the same, you actually compare their addresses from the memory and since they are different instances, they are not equal.

btw, regarding primitives, you compare the actual values (not the address)

omri_saadon
  • 10,193
  • 7
  • 33
  • 58