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.
Example:
In this example we only initialize the array and we are not adding any element in 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?
Different ways to declare array in javascript?
1) Declaring and populating array at the same time
2) Declaring array with array constructor: in this method we declare array with array constructor and then populate this array with the index. In javascript the array are not fixed length array type in other languages like c#,java this will grow dynamically even though they will declared with fixed length.
The array in JavaScript has length property which returns the size of that array.
Example:
Code:
var array = [];
console.log("Array Length -- "+ array.length);
Code:
var array = new Array(100);
console.log("Array Length -- "+ array.length);
How to retrieve first and last element in array?
Code:
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/>");
1) Declaring and populating array at the same time
Code:
var array=[10,20,30]; console.log(array);
Code:
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);
Comment