Manipulating Arrays
Explore the fundamental techniques for manipulating arrays in JavaScript, including adding and removing elements at both ends and modifying values by index. This lesson helps you understand practical array operations to prepare you for more advanced JavaScript coding.
We'll cover the following...
Adding elements to the beginning or end
You can add elements to the beginning and to the end of the array:
Pushadds elements to the end of the arrayUnshiftadds elements to the beginning of the array
Removing elements
You can also remove these elements from the array:
Popremoves the last element from the array and returns it.Shiftremoves the first element from the array and returns it.
Similarly to objects, you can delete any element from the array. The value 1 empty item will be placed in the place of this element. You will notice that the length of the array does not change after deleting days[2] because using the delete operator with arrays creates a hole in that place.
Note: It is recommended not to use
deleteoperator to remove an element from JavaScript arrays.
Overwriting and adding elements at any index
The values of an array can be set by using their indices and equating them to a new value. You can overwrite existing values or add new values to the array. The indices of the added values do not have to be continuous:
As with most topics, bear in mind that we are just covering the basics to get you started in writing code. There are multiple layers of knowledge on JavaScript arrays. We will uncover these lessons once they become important.
"push and shift are used for the same purpose."
Is the above statement correct?
Yes
No
Not sure