Other ways to define arrays

Space now, assign later

Space now, assign later method allows you to assign a certain amount of space (or elements) to an array and then, later in the script, assign the values.

var StudentsClass = new Array(4);

This creates an array called StudentsClass which will initially have four elements (you can add more elements later).

If you want to assign a value of “Dan” to the third element in the array then you use index number (index number 2 for third position).

StudentsClass[2] = "Dan";

You can add more elements to the initial array and give them values.

StudentsClass[4] = 'Flora";

This adds the fifth element, which has a value of “Flora” to the array.

Space now, assign numerically now

In Space now, assign numerically now method some or all of the elements of the array are assigned right after the array is created.

var StudentsClass = new Array(4);
StudentsClass[0] = "Tra";
StudentsClass[1] = "Sonia";
StudentsClass[2] = "Dan";
StudentsClass[3] = "Catalin";

This method is very useful for long lists of elements.

Array name, no parameters

The Array name, no parameters method, as the name suggests, allows you to create an array with no elements in it. You can add one or more elements to the array later in the script.

var StudentsClass = new Array();
//Here can go whatever another JavaScript code you want
StudentsClass[0] = "Tra";

You can assign a value to the element number 3 for example. In our case, where we have an array with no elements, means that the array will have now three elements. You can assign values for the other elements later in the script.

var StudentsClass = new Array();
//Here can go whatever another JavaScript code you want
StudentsClass[2] = "Dan";

Leave a Reply