https://blog.kevinchisholm.com
In this video, I’ll explain how to add an element to the end of a JavaScript Array.
In JavaScript, the push method adds one element to the end of an array. I’m going to take this example code and paste it here in the browser. I don’t need the comments, and for now we simply want to define the array, and then I’ll add on to the end.
So first let’s define the array. So now, when I inspect “foo,” we can see it has four elements. So now I’ll use the push method to add an element to the end of the array, and it returns the new length of the array. So calling the method actually returns the number four because that’s the new length of the array. If I type “foo.length,” I get four. Now, when I inspect “foo,” I see it’s got four elements.
So let’s say that I wanted to add another element to the end of the array, so I’ll call the push method again. Notice, again, how it has four elements now, and now I’ll use the push method to add one more element, and this will return the new length of the array, which will be five. Now the length is five. If I do “foo.length,” I get five. And when I inspect “foo,” you can see that it has five elements.
So can do it one more time. I’m going to use the push method to add one more element to the end of “foo.” So now it should have the letter “f” at the end of the array, as the last element, and the new length is six. And when I inspect “foo,” I see that it has six elements.
So, the push method will add whatever you pass to it to the end of an array. It will always make it the last element in the array, and it will 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 right 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.