At first glance, some might say: “Well, you are the programmer. So you know how long the array is and can dynamically append an element by doing the following: foo[x] = newElement. Right?” Well, yes, but that is not what we are really trying to do.
I think that most programmers will agree that what you want in this situation is to be able to add an element to the array, regardless of the length. What you want to assume is that you will not know the length. And from a pseudo-code perspective, you want to say: “Hey, I have an array named ‘foo’ and however long it is, add this new element named ‘newElement’ to the end of it.” I think that when you can accomplish that, you have significantly more power.
Array.prototype.push() – Example # 1
The syntax is: yourArray.push(WhatYouWantToAdd)
It’s literally that simple.
Using the array’s “length” property – Example # 2
In Example #2, we leverage the “length” property of the array. The reason this works so well is that the value of an array’s “length” property will always be exactly one higher than the index of the last element in the array. Why? Because while array indexes are zero-based (i.e. the first element in the array is element 0, and the second element in the array is element # 1, and the third element is element # 2, etc…), the array’s “length’”property is a one-based value (i.e., if there are three elements in the array, the length is: 3).
So, if the array “foo” has three elements, foo is the last element in the array, and the value of foo’s “length” property is “3”. Therefore, foo does not exist yet (remember foo is the last element).
Since we may not always know the length of the array when we need to dynamically append an element by simply adding a new element to the end, we can reference foo[.foo.length]. This way, no matter how many elements are in foo, we can simply assign the new element to foo[.foo.length].