Sobes.tech
Junior

What array methods modify its contents?

sobes.tech AI

Answer from AI

  • push() - adds one or more elements to the end of an array and returns the new length.
  • pop() - removes the last element from an array and returns its value.
  • shift() - removes the first element from an array and returns its value.
  • unshift() - adds one or more elements to the beginning of an array and returns the new length.
  • splice() - changes the contents of an array by removing existing elements and/or adding new ones.
  • sort() - sorts the elements of an array "in place" and returns a reference to the same array.
  • reverse() - reverses the order of the elements in an array "in place" and returns a reference to the same array.
  • fill() - fills all the elements of an array from a start index to an end index with a static value.
  • copyWithin() - copies a part of the array to another location within the same array "in place" and returns it, without changing its length.

Example of using splice():

// Create an array
const arr = [1, 2, 3, 4, 5];

// Remove 2 elements starting from index 1 (elements 2 and 3)
arr.splice(1, 2);

// arr now [1, 4, 5]