JavaScript Array shift()

Posted by

Method

Introduction to the JavaScript Array shift() Method

The JavaScript Array shift() method is used to remove the first element of an array and returns the removed element. The shift() method changes the length of the array, while the unshift() method is used to add new elements to the beginning of an array.

Syntax

The syntax of the shift() method is as follows:

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

array.shift();

[/dm_code_snippet]

Example

Let’s look at an example to understand how the shift() method works:

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

var fruits = ["Banana", "Orange", "Apple", "Mango"];

var firstElement = fruits.shift();

console.log(fruits);  // Output: ["Orange", "Apple", "Mango"]

console.log(firstElement);  // Output: Banana

[/dm_code_snippet]

In the above example, the shift() method is used to remove the first element of the fruits array and store it in the variable firstElement. Then, the remaining elements are printed out to the console.

Return Value

The shift() method returns the removed element from the array.

Browser Support

The shift() method is supported in all major browsers.