Last Updated On By Khizer Ali
The JavaScript array shift() is a built-in function that we use to remove the first item from an array (i.e., the element at 0 index position) and get that removed item. This method does not take any argument.
It changes the length of the array on which we are calling the shift() method. It directly modifies the array by removing the first element and returns that removed element, so the array shift() is not a pure function.
Table of Contents
array.shift()
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<p id="demo"></p>
<p id="demo1"></p>
<p id="demo2"></p>
<script>
let array = ["Mobile", "Earphones", "Laptop", "Charger"];
document.getElementById("demo").innerHTML = "Array before function calling :: " + array;
removed_item = array.shift();
document.getElementById("demo1").innerHTML = "Array shift() removed item :: " + removed_item;
document.getElementById("demo2").innerHTML = "Array after function calling :: " + array;
</script>
</body>
</html>
In the example above, we saw that before calling the shift() function on an array, it returned the entire array. However, on calling shift(), it is not returning us the entire array, but the only element that the shift() method removes from the array. And finally, after calling the method the output is again returning the entire array except for the element that we just removed.
We use the array shift() method inside while loop when we want to check a specific condition using the function shift().
Let’s see an example to clear the concepts.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<p id="demo"></p>
<script>
removed_item = "";
let array = ["Mobile", "Earphones", "Laptop", "Charger"];
while( (i = array.shift()) !== undefined ) {
removed_item += "<br>" + i + " Removed ";
}
document.getElementById("demo").innerHTML = "Array shift() removed items :: " + removed_item;
</script>
</body>
</html>
In the above example, we call the array shift() function inside the while loop condition. It removes each item of the array one by one because the loop will execute while the array becomes empty.
In this article, we looked at the array shift() method in JavaScript. We were using the array shift() method to remove the first item of the array and get that removed item. We also saw two different coding examples.