Kodeclik Blog
Javascript’s Array shift() method
Assume you are given a Javascript array such as the following:
<script>
const ages = [12,23,11,14]
document.write(ages)
</script>
The output will be, as expected:
12,23,11,14
Let us now apply the shift() method on this array and print it again:
<script>
const ages = [12,23,11,14]
document.write(ages)
ages.shift()
document.write('<BR>')
document.write(ages)
</script>
The output will be:
12,23,11,14
23,11,14
In addition to deleting the element shift() returns that value so we can use it programmatically, like so:
<script>
const ages = [12,23,11,14]
document.write('Before: ' + ages)
removed_value = ages.shift()
document.write('<BR>')
document.write('After removing ' + removed_value)
document.write('<BR>')
document.write('After: ' + ages)
</script>
The output will be:
Before: 12,23,11,14
After removing 12
After: 23,11,14
Note that the shift() method changes the original array and also returns the deleted element.
Javascript shift() with an empty array
Let us redo the last script above with an empty array:
<script>
const ages = []
document.write('Before: ' + ages)
removed_value = ages.shift()
document.write('<BR>')
document.write('After removing ' + removed_value)
document.write('<BR>')
document.write('After: ' + ages)
</script>
The output is:
Before:
After removing undefined
After:
Note that the return value is undefined because the array is empty. Further there are no modifications to the original array because there was no element left to remove.
Using Javascript shift() to remove multiple elements
We can embed the shift() method in a larger loop to cycle through each element of the array, removing them one by one. Here is a program to do just that:
<script>
const ages = [11,12,13,14,15]
document.write('Before: ' + ages)
while (ages.length) {
val = ages.shift()
document.write('<BR>')
document.write('Removing: ' + val)
}
document.write('<BR>')
document.write('After: ' + ages)
</script>
The while loop uses the length method to check if the array at the outset is not empty. If it is empty, it exits the loop. Inside the loop we shift() one element at a time, and print the element just removed.
The output of the above program is:
Before: 11,12,13,14,15
Removing: 11
Removing: 12
Removing: 13
Removing: 14
Removing: 15
After:
Would you like to learn more Javascript? Checkout our blog post on how you can use Javascript Math.max() to find the max element of an array.
Want to learn Javascript with us? Sign up for 1:1 or small group classes.