Tutorialspoint.dev

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:

    // 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);

    Output:

    34
    234,567,4
    

    Program 2:

    // 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);

    Output:

    undefined
    
    


    This article is attributed to GeeksforGeeks.org

    leave a comment

    code

    0 Comments

    load comments

    Subscribe to Our Newsletter