Open In App

JavaScript Array shift() Method

Improve
Improve
Like Article
Like
Save
Share
Report

JavaScript Array shift() Method removes the first element of the array thus reducing the size of the original array by 1.

Syntax:

arr.shift();

Parameters: This method does not accept any parameter.

Return Value: This function returns the removed first element of the array. If the array is empty then this function returns undefined.

Note: This function can also be used with other javascript objects that behave like the array.

JavaScript Array shift() Method Examples

Example 1: Removing the First Element from the Array

The function func() removes the first element from array using the shift() method. The removed element is stored in the variable, value, which is then logged to the console along with the modified array.

JavaScript
function func() {
    // Original array
    let array = ["GFG", "Geeks", "for", "Geeks"];

    // Checking for condition in array
    let value = array.shift();

    console.log(value);
    console.log(array);
}
func();

Output
GFG
[ 'Geeks', 'for', 'Geeks' ]

Example 2: Removing First Element from Empty Array

The function func() attempts to remove the first element from an empty array array using the shift() method. Since the array is empty, shift() returns undefined, which is logged to the console along with the unchanged array.

JavaScript
function func() {

    // Original array
    let array = [];

    // Checking for condition in array
    let value = array.shift();

    console.log(value);
    console.log(array);
}
func();

Output
undefined
[]

Example 3: Removing the First Element from the Nested Array

The function func() removes the first element from the nested array using the shift() method. The removed element is stored in the variable value, which is then logged to the console along with the modified array.

Javascript
function func() {
    // Original array
    let array = [1,[2,3,4],5,6];

    // shift method on nested array
    let value = array[1].shift();

    console.log(value);
    console.log("Array after operation: "+ array);
}
func();

Output
2
Array after operation: 1,3,4,5,6

Supported Browsers:

We have a complete list of Javascript Array methods, to check those please go through this Javascript Array Complete reference article.

We have a Cheat Sheet on Javascript where we covered all the important topics of Javascript to check those please go through Javascript Cheat Sheet-A Basic guide to JavaScript.


Last Updated : 14 Mar, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads