How to Check If Two Arrays Are Equal in JavaScript
To check if two arrays are equal in JavaScript, compare their lengths first, then check each element one by one using a loop or
Array.prototype.every(). Simple equality operators like == or === do not work because they compare references, not content.Syntax
To compare two arrays, you typically write a function that:
- Checks if both arrays have the same length.
- Compares each element at the same position.
This can be done using a for loop or the every() method.
javascript
function arraysEqual(arr1, arr2) { if (arr1.length !== arr2.length) return false; return arr1.every((value, index) => value === arr2[index]); }
Example
This example shows how to use the arraysEqual function to check if two arrays are exactly the same.
javascript
function arraysEqual(arr1, arr2) { if (arr1.length !== arr2.length) return false; return arr1.every((value, index) => value === arr2[index]); } const array1 = [1, 2, 3]; const array2 = [1, 2, 3]; const array3 = [3, 2, 1]; console.log(arraysEqual(array1, array2)); // true console.log(arraysEqual(array1, array3)); // false
Output
true
false
Common Pitfalls
Many beginners try to compare arrays using == or ===, but these check if both variables point to the same array in memory, not if their contents are equal.
Also, comparing arrays with nested arrays or objects requires deeper checks, not just simple equality.
javascript
const a = [1, 2, 3]; const b = [1, 2, 3]; console.log(a === b); // false - compares references, not content // Correct way: function arraysEqual(arr1, arr2) { if (arr1.length !== arr2.length) return false; return arr1.every((value, index) => value === arr2[index]); } console.log(arraysEqual(a, b)); // true
Output
false
true
Quick Reference
Remember these key points when comparing arrays:
- Use length check first to avoid unnecessary comparisons.
- Use
every()or a loop to compare elements one by one. - Simple
===checks only if arrays are the same object. - For nested arrays or objects, use deep comparison libraries or write recursive checks.
Key Takeaways
Arrays must have the same length and matching elements to be equal.
Use a function with
every() or a loop to compare array contents.Do not use
== or === to compare arrays directly.For nested structures, simple equality checks are not enough.
Checking length first improves performance by skipping unnecessary comparisons.