javascript
  1. javascript-shift

JavaScript shift()

The shift() method in JavaScript is an array method that removes the first element from an array and returns that element. This method changes the length of the array.

Syntax

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

array.shift()

Example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Array Pop Example</title>
</head>
<body>

<!-- Placeholder for displaying the output -->
<p id="output"></p>

<script>
    // Array
    let fruits = [1,2,3];

    // Remove the last element and store it in a variable
    let lastFruit = fruits.shift();

    // Display the removed element
    document.getElementById("output").innerHTML += "Removed Fruit: " + lastFruit + "<br>";

    // Display the modified array
    document.getElementById("output").innerHTML += "Remaining Fruits: " + fruits.join(', ');
</script>

</body>
</html>
Try Playground

Output

In the above example, the output of will be [2, 3] and the output of will be 1.

Explanation

The shift() method works by removing the first element from the array and then shifting all the remaining elements down by one index. The first element is then returned. If the array is empty or undefined, the shift() method will return undefined.

Use

The shift() method can be used to remove the first element of an array. This is useful when you only need to access the first element and want to remove it immediately. It is also useful when you are iterating over an array and want to remove elements one by one from the beginning.

Important Points

  • The shift() method modifies the original array and returns the shifted element.
  • If the array is empty, shift() returns undefined.
  • The shift() method is the opposite of the push() method which adds elements to the end of an array.

Summary

The shift() method in JavaScript removes the first element of an array and returns it. It can be useful for situations where you only need to access the first element, or when iterating over the array and removing elements one by one from the beginning. However, it does modify the original array, so caution should be taken when using it.

Published on: