JavaScript | Array shift()

arr.shift() function removes the first element of the array thus reducing the size of the original array by 1.

Syntax:
arr.shift()

Arguments

This function does not take any argument.



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.

    Example 1:

    var arr = [34, 234, 567, 4];
    print(arr.shift());
    print(arr);
    

    Output:

    34
    234,567,4
    

    In this example the function shift() removes the first element of the array, therefore it returns 34.

    Example 2:

    var arr = [];
    print(arr.shift());
    print(arr);
    

    Output:

    undefined
    

    In this example the function shift() tries to remove the first element of the array, but the array is empty, therefore it returns undefined.

    Codes for the above function are provided below:

    Program 1:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // JavaScript to illustrate 
    // shift() function
    importPackage(java.io);
    importPackage(java.lang);
    importPackage(java.math);
    importPackage(java.util);
      
    // Original Array
    var arr = [34, 234, 567, 4];
      
    // Removing the first element
    var value = arr.shift();
    print(value);
    print(arr);

    chevron_right

    
    

    Output:

    34
    234,567,4
    

    Program 2:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // JavaScript to illustrate
    // shift() function
    importPackage(java.io);
    importPackage(java.lang);
    importPackage(java.math);
    importPackage(java.util);
      
    // Original Array
    var arr = [];
      
    // Removing the first element
    var value = arr.shift();
    print(value);
    print(arr);

    chevron_right

    
    

    Output:

    undefined
    
    


    My Personal Notes arrow_drop_up

    Check out this Author's contributed articles.

    If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

    Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




    Article Tags :

    Be the First to upvote.


    Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.