To add a new element to an array, you just assign a value to the element. For example, let’s assume you have an array with two elements:
var myArray = new Array(2); myArray = "dog"; myArray = "cat";
The following assignment:
myArray = "snake"
adds an element with an index of 2 and a value of "snake" to myArray.
To determine if a variable (or array element) exists and has a value, you can compare the value to undefined. (I provide an example of this in the section “ Iterating Through an Array.”)
Conversely, if you want to get rid of the value of an array element, you can simply assign the special value undefined to the array element at a specific index. Note that this doesn’t actually remove the element, it just makes the value of the element undefined.
For example, let’s take the four-element array created with these statements:
var myArray = new Array(4); myArray = "dog"; myArray = "cat"; myArray = "snake"; myArray = "dragon";
You can now delete the fourth (and last) element from the array by executing this statement:
myArray = undefined;
You can also delete an element in an array using the delete method. The statement delete myArray; is equivalent to the statement myArray = undefined;.
To say that an array is sparse means that the values of the index for the array doesn’t need to be a contiguous range of numbers. Space in the computer’s memory is only allocated for the array elements that are actually stored in the array (and not for elements that are undefined).
For example, the following statements create an array with four defined elements:
var myArray = new Array(); myArray = "dog"; myArray = "cat"; myArray = "snake"; myArray = "dragon";
As you’ll see in a moment, the value of the length property of this array is 3001; however, only the four elements referenced in these statements (with an index value of 500, 1000, 2000, and 3000) have been allocated space in memory.