1

how is [1,2,3]==[1,2,3] and [1,2,3]===[1,2,3] false? Would appreciate a simple explanation. Came across this while watching a youtube video.. anymore "anomalies" like this?

eniigma
  • 39
  • 4

3 Answers3

0

The == operator checks whether the two operands reference the same object. While the two objects (arrays are objects) may have the same content, they are different instances, and thus the expression is false.

Spectric
  • 30,714
  • 6
  • 20
  • 43
0

The === and == operators compares arrays by reference (i.e. location in memory), the easy way to think about it is that "they are different arrays with the same values".

If you give you arrays a name, maybe the reason for this will be clearer:

const arr1 = [1, 2, 3];
const arr2 = [1, 2, 3];

console.log(arr1 === arr2);

And arr1 is not the same array as arr2.

Conversely, this will log true, because it compares the same reference:

const arr = [1, 2, 3];

console.log(arr === arr);
mausworks
  • 1,607
  • 10
  • 23
  • "Reference" might not be the right word here. I know this is saying almost the same thing, but it's more like the variable has a value. Since JS doesn't really have references like C. – evolutionxbox Dec 19 '21 at 02:02
  • JavaScript does have references. [Objects are all passed as references](https://www.freecodecamp.org/news/how-to-get-a-grip-on-reference-vs-value-in-javascript-cba3f86da223/): If you pass an array into a function, it doesn't pass the _values_ into said function, it just passes the reference to the array. Are you conflating references with pointers? – mausworks Dec 19 '21 at 02:10
  • JS uses [call-by-sharing](https://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_sharing), which is essentially pass-by-value. – evolutionxbox Dec 19 '21 at 02:12
  • While it's not a reference _strict meaning_, it's a reference in a _practical meaning_. I don't think that language implementation minutia is important to understand why `[] === []` returns `false`, do you? – mausworks Dec 19 '21 at 02:22
  • Practically I don't think it actually makes a difference, tbh. I use the concept that all literals are unique. – evolutionxbox Dec 19 '21 at 02:26
-1

They are not equal because they are not the "same". In js, if you do [1,2,3] it stores the array as a variable with no name. Give it a name, say 'r', and do r==r and it will return true because window.r is the same as window.r. But window.undefinedvariable0 is not the same as window.undefinedvariable1, although they are visually the same.

Hermanboxcar
  • 418
  • 1
  • 13