How to add an element to the beginning of a JavaScript Array - Array.prototype.unshift()

Опубликовано: 21 Октябрь 2017
на канале: Kevin Chisholm
319
3

https://blog.kevinchisholm.com

In this video, I'll explain how to add an element of the beginning of a JavaScript Array.

In JavaScript, the unshift method adds an element to the beginning of an array and returns the new length of the array. Here, I have an array called "foo," with three elements. If I call the unshift method, and pass it to letter "C," it should add the letter "C" to the beginning of the array, and return the new length of the array, which would be four.

Let's give it a try. So, first in the console, I want to define the array. So, I'm going to create this array called "foo," that's got three elements, and I can inspect that, just to confirm that, and I see it's got three elements. So, now if I call the unshift method on "foo," and pass the letter "C," it should add "C" to the beginning of the array and return the new length of the array, which would be four.

So, it returns four, and now when I inspect "foo," I see that "foo" has a new element at the beginning of the array. So, it's added an element to the beginning of the array. If I call the unshift method and pass the letter "B," it should add the letter "B" to the beginning of the array, and return a new length, which should be five. And the new length is five, and when I inspect the array, I see that it has a new element in the beginning of the array, which is "B."

Now I'll try one more. I'll call "foo" unshift and pass it to letter "A," and return the new length of the array, which is six, and if I inspect "foo" I can see it has a new element on the beginning, which is the letter "A."

So, in JavaScript, the unshift method will add an element to the beginning of an array, and always return the new length of the array.

If you found this video helpful, you can subscribe to my channel by clicking the red "subscribe" button under the video. And you can also visit my blog, where I have many more articles and tutorials about web development.


Thanks very much for watching.