Follow The New Tutorial updates on WhatsApp, Telegram or YouTube.

JavaScript Array shift() method

The JavaScript array shift() method removes the first element of the given array and returns that element.

JavaScript Shift is an inbuilt Array method.

JavaScript Array shift() method changes the length of the original array.

The shift() method returns the shifted element.

The shift method removes the element at the 0th index and shifts the values at consecutive indexes down, then returns the removed value. If the length property is 0, undefined is returned.

In arr = [ “a”,”b”,”c”] after Shift is used the element “a” is removed and the subsequent elements are moved up 1 index, i.e “b” whose index was 1 initially is moved to 0.

The JavaScript Shift() function reduces the size of the array by 1.

Syntax

array.shift()

Parameters: This method does not accept any parameter.

Return Value

The removed element from the array; undefined if the array is empty. A string, a number, an array, or any other type allowed in an array.

Example

Below are the example of Array shift() method.

const array1 = [1, 2, 3];

const firstElement = array1.shift();

console.log(array1);
// expected output: Array [2, 3]

console.log(firstElement);
// expected output: 1
var myFish = ['angel', 'clown', 'mandarin', 'surgeon'];

console.log('myFish before:', JSON.stringify(myFish));
// myFish before: ['angel', 'clown', 'mandarin', 'surgeon']

var shifted = myFish.shift();

console.log('myFish after:', myFish);
// myFish after: ['clown', 'mandarin', 'surgeon']

console.log('Removed this element:', shifted);
// Removed this element: angel
//implementation of javascript shift function
var fruits = ["Apple", "Mango", "Oranges", "Banana"];
var shifted = fruits.shift();

console.log(fruits);
//array after Javascript Shift was used
// [ "Mango", "Oranges", "Banana" ]

console.log(shifted);
//Element that was retuned
//Apple