By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
462,924 Members | 574 Online
Bytes IT Community
Submit an Article
Got Smarts?
Share your bits of IT knowledge by writing an article on Bytes.

Arrays In JavaScript

P: 17
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.

Expand|Select|Wrap|Line Numbers
  1. var array = [];
  2. console.log("Array Length -- "+ array.length);

Expand|Select|Wrap|Line Numbers
  1. var array = new Array(100);
  2. console.log("Array Length -- "+ array.length);
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?
Expand|Select|Wrap|Line Numbers
  1. var array = [100,200,300]
  2. console.log("First Element -- " +array[0]);
  3. console.log("Last Element -- " + array[array.length-1]);
  5. document.write("Array Is " + array+"<br/>");
  7. document.write("First Element -- " + array[0] + "<br/>");
  8. document.write("Last Element -- " + array[array.length - 1] + "<br/>");
Different ways to declare array in javascript?

1) Declaring and populating array at the same time
Expand|Select|Wrap|Line Numbers
  1. var array=[10,20,30];
  2. console.log(array);
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.
Expand|Select|Wrap|Line Numbers
  1. var constructor_array = new Array(2);
  2. constructor_array[0] = 10;
  3. constructor_array[1] = 20;
  4. constructor_array[3] = 30;
  5. console.log(constructor_array);
  6. console.log("Second Array Length - "+constructor_array.length);
Dec 31 '19 #1
Share this Article
Share on Google+
1 Comment

Expert Mod 5K+
P: 5,390
while all this is trivial - the preferred method to declare an array in JavaScript is always with the array literals:

Expand|Select|Wrap|Line Numbers
  1. let arr = [];
there is no reason to allocate memory for elements that are not yet in the array since it can grow dynamically. Even tho other possibilities exist - in all the years i am working with JavaScript already - i never had a reason to use another way of declaring an array as by the literals.

A comprehensive doc about arrays, and especially the methods it provides, can be found here:
Jan 2 '20 #2