How to remove JavaScript Array elements by Pop/Shift methods?

Removing elements from JavaScript arrays can be accomplished by using pop and shift methods.

The JavaScript pop method removes the last element from an array. If you need to remove elements from the beginning of an array then use the JavaScript shift method. Both of these methods are explained below with the online example and JS code.

The array pop method

The JavaScript array pop method removes array element from the last of an array. The syntax to use the pop method is:

Arrayname.pop();

The pop method returns the deleted element from the array. If you assign this to a variable, you can get the value of that element as shown in the following example.

An array remove example by using the pop method

The following example shows how to use the array pop method to delete the element from an array. For our example, we have created an array of four numbers.

After that, we used the JavaScript pop method and assigned it to a variable. The variable’s value is shown in an alert while array after using the pop method is displayed in an HTML paragraph. See the demo by clicking the link or image below:

Experience this example online

The shift method

If you need to remove the array elements from the beginning of an array then use the javaScript shift method. The shift method also returns deleted array element.

Delete element from array example by shift method

The following example deletes the element from an array by using the shift method. We have created an array of four numbers. Then a variable is assigned the return the value of shift JavaScript method. As example page loads, the alert will show removed

As example page loads, the alert will show the removed element. The array elements are then displayed in HTML paragraph after using the shift method.

Experience this example online

You can see, the array element is removed as the demo page loaded. While the array is displayed without the first removed element.

JavaScript clear array example

The pop and shift methods only remove the last and first element of the given array, respectively. What, if you need to remove all elements of an array? Following are few ways to clear array elements.

You can use the length property of array and set the array value to 0. See example below:

Experience this example online

You can see a cleared array as no elements are displayed.

You can also redefine array as blank [] if an array has no references to clear the array.