How to compare arrays in JavaScript?

To compare arrays in JavaScript, first compare lengths, then compare elements at same positions with each other.

Here's the code:

function areArraysEqual(array1, array2) {
  if (array1.length !== array2.length) {
    return false;
  }

  for (let i = 0; i < array1.length; i++) {
    if (array1[i] !== array2[i]) {
      return false;
    }
  }

  return true;
}

Let's test it:

// false
console.log(areArraysEqual(
  [ 1, "a string", 35, false ],
  [ 1, "a string", 3 ]));

// true
console.log(areArraysEqual(
  [ 1, "a string", 35, false ],
  [ 1, "a string", 35, false ]));