Final answer:
To check if two arrays are equal in JavaScript, write a function that compares the length of the arrays and each corresponding element for equality. Use a for loop to iterate over the elements. If all checks pass, the arrays are equal.
Step-by-step explanation:
To check whether two arrays are equal in JavaScript, you compare each element in the arrays to ensure they have the same values in the same order. Because arrays are reference types, simply using == or === won't work, as they compare references rather than values. Here's a function to check if two arrays are equal:
function arraysAreEqual(arr1, arr2) {
if (arr1.length !== arr2.length) return false;
for (let i = 0; i < arr1.length; i++) {
if (arr1[i] !== arr2[i]) {
return false;
}
}
return true;
}
To use this function, simply call it with the two arrays you want to compare as arguments:
const array1 = [1, 2, 3];
const array2 = [1, 2, 3];
console.log(arraysAreEqual(array1, array2)); // Outputs
true