Introduction
An array is a collection and it is zero-indexed. The meaning of this is the first element is at index zero and the last element is at an index of array length -1 position. The array in JavaScript has length property which returns the size of that array.
- var array = [];
- console.log("Array Length -- "+ array.length);
- var array = new Array(100);
- console.log("Array Length -- "+ array.length);
In this example, we only initialize the array without adding any element in an array. If you see the output, you will see we
initialize at 100 and length is also 100.
How to retrieve first and last element in array?
- var array = [100,200,300]
- console.log("First Element -- " +array[0]);
- console.log("Last Element -- " + array[array.length-1]);
-
- document.write("Array Is " + array+"<br/>");
-
- document.write("First Element -- " + array[0] + "<br/>");
- document.write("Last Element -- " + array[array.length - 1] + "<br/>");
Different ways to declare an array in Javascript
Declaring and populating an array at the same time
- Var array=[10,20,30];
- Console.log(array);
Declaring array with array constructor: In this method, we declare an array with an array constructor and then populate this array with the index. In Javascript, arrays are not a fixed length as are the array type in other languages, such as C#. In Java, this will grow dynamically even though they are declared with a fixed length.
- var constructor_array = new Array(2);
- constructor_array[0] = 10;
- constructor_array[1] = 20;
- constructor_array[3] = 30;
- console.log(constructor_array);
- console.log("Second Array Length - "+constructor_array.length);