Deleting Elements from Arrays

By: Dusty Arlia
Published on September 19, 2012
Last Updated on Tuesday, July 07, 2015 at 9:36 PM
Total Updates: 5

When you're working with arrays and you would like to remove an element, there are two different JavaScript methods you can use: pop() and shift(). These both remove one element at a time.

The JavaScript pop() method will remove the last element from the end of an array. Here's how the code would look:

var daysOfTheWeek = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'];
daysOfTheWeek.pop();

The resulting array would be: ['Monday', 'Tuesday', 'Wednesday', 'Thursday']. As you can tell the string Friday gets removed from the array. If you would like to store that removed string in a variable, you can change your last line of code to look like this:

var removedElement = daysOfTheWeek.pop();

The JavaScript shift() method will remove the first element from the beginning of an array. Here's how the code would look:

var daysOfTheWeek = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'];
daysOfTheWeek.shift();

The resulting array would be: ['Tuesday', 'Wednesday', 'Thursday', 'Friday']. As you can tell the string Monday gets removed from the array. If you would like to store that removed string in a variable, you can change your last line of code to look like this:

var removedElement = daysOfTheWeek.shift();

Comments:

Ad: