This short tutorial will show you how to use the JavaScript Array.shift() method to remove items from an array, and provide some code examples.
JavaScript Arrays
An array is a variable type which can hold zero or more values within it. Each value in an array has a position, called the index – which is an integer value representing the items position in it’s order of appearance. Indexes start counting at position 0 – so the first item in an array is at index 0, the second item at index 1, and so on.
JavaScript arrays are usually defined using the following syntax:
var myArray = [1, 2, 3]; // Define an array containing the numerical values 1, 2, 3
Remove The First Item From an Array With The Array.shift() Method
The shift() method will remove the first item (the item at index 0) from an array and return it.
JavaScript Array.shift() Syntax
The syntax for the shift() method is as follows:
array.shift()
Note that:
- array can be any array type variable
- It can be empty
- shift() will remove the element from the array it is called from
- shift() will return the value of the removed element
- If the array is empty, a value of undefined will be returned
JavaScript Array.shift() Examples
The following code example shows how the shift() method is used with JavaScript arrays:
var myArray = [1, 2, 3]; // Define an array containing the numerical values 1, 2, 3 console.log(myArray); // Print the array to the console for inspection var removedElement = myArray.shift(); // Call the shift() method on the array to remove the first element from the array and assign the value to the variable removedElement console.log(myArray); // The array will now have the value [2, 3] console.log(removedElement); // The variable removedElement will contain the value of the element removed from the array
The below example illustrates what happens when shift() is called on an empty array:
var myArray = []; // Define an empty array var removedElement = myArray.shift(); console.log(removedElement); // removedElement will have a value of undefined