JavaScript Arrays

In simple words an array is a special variable, which can hold more than one value at a time. An array is a collection of values that are belonging to a same data type. Each value is an element of the array and has an associated index number. We can refer to a particular element in the array by using the name of the array and the index number. The index number starts at zero. The list of array values that are separated by comma and must have to belong between opening and closing bracket. In JavaScript we can create array with two methods. Now lets see the first one :
  var array_name = [value1, value2, value3, ......, value_n];
Where :
  • array_name is the name of the array.
  • value1, 2, 3,..n are the values of array separated by comma.

For example :
  var mycars = ["BMW", "TOYOTA", "NISSAN", "FORD"];
The above method is a simple method to create an array in JavaScript, and the other method of creating array is by using keyword new :
  var array_name = new Array(value1, value2, value3, ...., value_n);
For example :
  var array_name = new Array("BMW", "TOYOTA", "NISSAN", "FORD");
Where the new Array() is JavaScript Built-in Array Constructor method used to create an array. The above two syntax do exactly the same thing, so for simplicity, readability and execution speed the first one is preferred. And in case if you want to create an empty array with a specific size then use the below syntax :
  var array_name = new Array(array_size);
Where the array_size indicates the maximum number of values the array can be stored.

Accessing The Array Elements :

The elements or values of an array can be accessed by the index numbers. The array index will start with 0, which indicates the first value of an array. For example :
  var names = ["John", "kumar", "Jack", "Tom"];
where, the value can be accessed by :
  names[0] = "John"
  names[1] = "kumar"
  names[2] = "Jack"
  names[3] = "Tom"
Example 1 :
<!DOCTYPE html>
<html>
<body>
  <script>
    var names = ["John", "Kumar", "Jack", "Tom"];

    for(var x = 0; x < 4; x++) {
      document.write(names[x] + "<br/>");
    }
  </script>
</body>
</html>
Output :


Example 2 :
<!DOCTYPE html>
<html>
<body>
  <script>
    var subjects = new Array(5);
    subjects[0] = "Mathematics";
    subjects[1] = "Physics";
    subjects[2] = "Chemistry";
    subjects[3] = "Social Science";
    subjects[4] = "Environment Studies";

    for(var x = 0; x < 5; x++) {
      document.write(subjects[x] + "<br/>");
    }
  </script>
</body>
</html>
Output :


At above in both examples we are used for loop to get all the array elements.

Next Topic :