How do you add, remove, and update elements in an array?
TL;DR
To add elements to an array, you can use methods like push
, unshift
, or splice
. To remove elements, you can use pop
, shift
, or splice
. To update elements, you can directly access the array index and assign a new value.
Adding elements to an array
Using push
The push
method adds one or more elements to the end of an array and returns the new length of the array.
Using unshift
The unshift
method adds one or more elements to the beginning of an array and returns the new length of the array.
Using splice
The splice
method can add elements at any position in the array. The first parameter specifies the index at which to start changing the array, the second parameter specifies the number of elements to remove, and the rest are the elements to add.
Removing elements from an array
Using pop
The pop
method removes the last element from an array and returns that element.
Using shift
The shift
method removes the first element from an array and returns that element.
Using splice
The splice
method can also remove elements from any position in the array. The first parameter specifies the index at which to start changing the array, and the second parameter specifies the number of elements to remove.
Updating elements in an array
Direct assignment
You can update elements in an array by directly accessing the index and assigning a new value.