Search code examples
javascriptsyntaxexpressionecmascript-5

Whys is ["text"] == ["text"] false?


Why does the expression ["text"] == ["text"] evaluate to false in JavaScript?

I intuitively expected it to be true, since the two arrays are identical. Is the JS engine comparing references to two different objects, and thus returning false, instead of comparing the contents of the arrays?


Solution

  • You have created two different arrays and JavaScript is comparing their references, not their content.

    const array = [1, 2, 3];
    
    // evaluates to true
    console.log(array === array);
    
    // evaluates to false
    console.log([1, 2, 3] === [1, 2, 3]);

    Here is a very well constructed answer on comparing the contents of arrays: How to compare arrays in JavaScript?