To add an element, we can simply identify the element using a new index and assign a value to it; e.g. we can add a new (sixth) element to arraySmall of above figure as: "arraySmall = 680"; an index of 5 means that the new element is in fact the sixth element.
Sometimes, we may find it more compact to use a single step to not only define an array but to also add some initial values to it. To do this, both of the above array-definition methods accept initial values. For the first case, we can use "var arraySmall = ["Elves", "Goblins", 101.280, [1,2,3], "Merlin"] ". For the second case, we can use "var arraySmall = new Array("Elves", "Goblins", 101.280, [1,2,3], "Merlin")".
Before we go any further, let us use a simple example to demonstrate array definition. This example (provided below) uses both of these methods to define arraySmall. Further, this example implements a "printArray()" function to print array elements.
The output (provided below) prints array elements identically for both arrays. Note to self, this being the first example should be provided as an image and not as a simple text output.
Nevertheless, using for/in loops comes with two cautionary notes. First, when it lists object properties (and in this case array indexes), it may not list them in the exact order as they were defined. If ordering is important, we should stick with using a for loop. Second, with arrays, it may skip those records that have been deleted.
We provide the output below. As explained earlier, the length of the array remains unchanged even after deleting its elements.
After deletion, the Length is: 5 Printing using a for loop: [index: 0] value: undefined [index: 1] value: undefined [index: 2] value: 101.28 [index: 3] value: 1,2,3 [index: 4] value: Merlin Printing using a for/in loop: [index: 2] value: 101.28 [index: 3] value: 1,2,3 [index: 4] value: Merlin