Populating an array

After you create an array, we can start storing values in to the array. To populate an array with values, you need to use the name of the array, the index (indicated inside square brackets []) where you want to store a value, and the value you want to store. For instance,

var URLsArray = new Array (4);
URLsArray [0] = "http://www.scriptingmaster.com";
URLsArray [1] = "http://www.scripting-master.com";
URLsArray [2] = "http://www.scriptingmaster.org";
URLsArray [3] = "http://www.masterscripting.com";

On line 1, we declare an array called URLsArray and of size 4. Then, on lines 2 through 5, we populate the array with different website addresses. Beside using the index value inside the square brackets, the array is initialized similar to a variable.

In JavaScript, you can also initialize an array at the time you create the array by specifying the values as arguments to the Array () method. Note each value must be separated by a comma. For instance,

var URLsArray = new Array ("http://www.scriptingmaster.com", "http://www.scripting-master.com", "http://www.scriptingmaster.org", "http://www.masterscripting.com");

we declare an array called URLsArray and populate it the same values we used for the last example. If you populate your array this way, the size of the array is determined by the values you supply to the Array () remember though each value must be separated by a comma. The size of the array As a visualization, see the following table how to understand how data inside an array is stored:

index value
0 "http://www.scriptingmaster.com"
1 "http://www.scripting-master.com"
2 "http://www.scriptingmaster.org"
3 "http://www.masterscripting.com"

In the following example, we use a for loop to populate our array:

<script language="javascript">
var numArr = new Array (10);
var i;
for (i = 0; i < 10; i++)
numArr[i] = i * i;
i = 0;
while (i < 10)
document.write ("numArr[" + i + "] = " + numArr[i] + "<br>");;

In this example, we create an array called numArr of size 10. We populate this array with numerical values using a for loop, see lines 4 through 8. The first time the for loop executes, numArr[0] is assigned 0 because i is 0 so 0 * 0 = 0. When the second time the loop executes, i becomes 1 and numArr[1] is assigned 1 because 1 * 1 = 1. The third time the loop executes, numArr[2] is assigned 4 and see below for other values populated to the array.

The i = 0; reinitializes i to 0 because after the for loop stops i was 10. We use variable i again in the while loop to print the values of the array. Again, to access the array we use the name of the array and an index value; for instance, to access the fourth element of numArr array, we would write numArr[3]. Remember array starts at index 0, so the first element is at index 0; second element at idnex 1, third element at index 2, etc. The following shows the output of our code: