Adding an element to the beginning of a JavaScript array. The JavaScript unshifted method provides a very simple way to add one element to the beginning of a JavaScript array. So if we take their foo array again, and let's say now it only has two elements, two letters B, and C, and I want to add letter A to the beginning of this array, well, then I could call the unshifted method and just pass it the letter A, and it would add it to the beginning of the array. And when I do that, then food now has a letter at the beginning. So I've added an element to the beginning of the array. But then why do I have litter the number three just floating there in the screen?
Well, the unshifted method always returns the new length of the array. So if I were to call on shift again, and let's say I'm passing it the number zero, if I call foo on shift and pass at zero, it adds zero to the beginning of the array, but it returns a number four, because four is a new length of the array. think this will make sense. If we look at a code example for this one. in JavaScript, the unshipped method adds an element 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 unshifted method and pass it the 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 unshifted method on foo, and add the letter C, pass the letter C, it should add c to the beginning of the array and return the new length of the array, which will be four, so returns four.
And now when I inspect foo, I see that foo has a new element to the beginning of the array, so it's added an element to the beginning of the array. If I call the unshifted method and pass the letter B, it should add look Be to the beginning of the array and return 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. I'll try one more, I'll call foo on shift and pass it the letter A, it returns a loop 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 unshifted method will add an element to the beginning of an array and always return the new length of the array.