- Full Stack Express
- Pages
- How to Add or Remove an Element at the End of an Array
How to Add or Remove an Element at the End of an Array in JavaScript
Let's begin with an array of colors:
const colors = ['red', 'blue', 'green'];
We can add the color yellow
to the end of our array:
colors.push('yellow');
Now, our array contains four different colors:
console.log(colors) // prints 4;
We can also push multiple elements at the same time:
colors.push('orange', 'gray', 'black');
Now, we have a total of seven colors in our array:
console.log(colors) // prints 7
If we want to remove elements from the end of the array, we can use the Array.pop()
method:
colors.pop();
Finally, we're left with an array containing only six elements:
console.log(colors); // prints [ 'red', 'blue', 'green', 'yellow', 'orange', 'gray' ]