< / >
Published on

Array methods and empty slots

There are several Array methods in JavaScript that have special treatment for empty slots. These methods include:

  • concat(): Returns a new array that concatenates the original array with other arrays or values. Empty slots are preserved in the resulting array.
const array1 = ['a', 'b', 'c'];
array1[5] = "p";
const array2 = ['d', 'e', 'f'];
const array3 = array1.concat(array2);

console.log(array3);
// Expected output: Array ["a", "b", "c", undefined, undefined, "p", "d", "e", "f"]
  • copyWithin(): Copies a sequence of array elements within the array. Empty slots are also copied.
const array1 = ['a', 'b', 'c', 'd', 'e'];

// Copy to index 0 the element at index 3
console.log(array1.copyWithin(0, 3, 4));
// Expected output: Array ["d", "b", "c", "d", "e"]

// Copy to index 1 all elements from index 3 to the end
console.log(array1.copyWithin(1, 3));
// Expected output: Array ["d", "d", "e", "d", "e"]