How to remove the first element of a JavaScript Array - Array.prototype.shift()

preview_player
Показать описание

In this video, I'll explain how to remove the first element of a JavaScript array. In JavaScript, the shift method removes the first element of an array, and returns that element.

Here, I have an array with six elements. The first element is the letter "A," so if I call the shift method on that array, it should remove the first element, which is the letter "A" and return it. Let's give it a try.

So first, I'll define this array and I now have an array called "foo," that has six elements, and the first element is the letter "A." So now, if I call the shift method on this array, it should remove the first element, which is the letter "A," and it should return that element. So, return the letter "A," and if I examine the array, we can see that it did remove the first element, which is the letter "A."

So, if I call the shift method again, it returns the letter "B," and I can see that if I examine foo, the letter "B" is missing, and the letter "C" is now the first element, and there'sonly four elements in the array. So, if I call shift one more time, it removed the first element, which is the letter "C," and if I examine foo, I can see it only has three elements, because the first element of "C" was removed the first element is "D."

So, in JavaScript, the shift method always removes the first element of an array, and it returns the element that it removed.

If you found this video helpful, you can subscribe to my channel by clicking the red "subscribe" button right under the video. You can also take a look at my blog, where there are many articles and tutorials about web development.

Thanks very much for watching.
Рекомендации по теме