## why is an identical array not equivalent?

Question

e.g.

``````\$  node
> [1, 2, 3] == [1, 2, 3]
false
``````

Apologies if I am using "identical" and "equivalent" incorrectly.

``console.log([1, 2, 3] == [1, 2, 3]);``

I ask, because I am used to languages such as Ruby

``````\$  irb
irb(main):001:0> [1,2,3] == [1,2,3]
=> true
``````

...or Python

``````\$  python
>>> [1,2,3] == [1,2,3]
True
``````

... where the double equals is comparing the value of the expression

Show source
2017-08-08 21:08 3 Answers

## Answers to why is an identical array not equivalent? ( 3 )

1. They are different locations in memory. They are two completely different arrays that just happen to have the same values.

It's like saying Person A and Person B are both carrying 3 apples, are they the same person? Person A cannot be Person B.

2. This [1,2,3] is an array object. When you create it you get a reference to this array, a pointer to a place in memory. By calling [1,2,3] you create another array and you get a completely different reference, a pointer to a completely different place in memory. The arrays you have created in both cases contain the same elements, the same amount of memory has been reserved for their creation, but they are actually two completely different objects.

The equality between two objects is based on comparing their references, if they are the same, then the references point to the same object so the evaluation of the `==` operator is `true`. Otherwise is `false`.

As it is stated more formally here:

Equality (==)

The equality operator converts the operands if they are not of the same type, then applies strict comparison. If both operands are objects, then JavaScript compares internal references which are equal when operands refer to the same object in memory.

3. Because while they may have the same content, they don't point to the same reference in memory.

For more precision, imagine the following example

``````let arr1 = [1,2,3]
let arr2 = [1,2,3]
arr1 == arr2 //false
``````

it makes sense, because the two arrays are different objects, even if they have similar values, for example if we then did

``````arr1.push(4)
``````

only arr1 would change.

If you are looking for a solution to comparing arrays, you might find this thread useful.