Kodeclik Logo

Our Programs

Courses

Learn More

Schedule

Kodeclik Blog

Javascript’s Array shift() method

Assume you are given a Javascript array such as the following:

The output will be, as expected:

Let us now apply the shift() method on this array and print it again:

Javascript Array Shift

The output will be:

In addition to deleting the element shift() returns that value so we can use it programmatically, like so:

The output will be:

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:

The output is:

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:

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:

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.

Kodeclik sidebar newsletter

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.

About

Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.

Copyright @ Kodeclik 2024. All rights reserved.