You are on page 1of 2

Introduction to Arrays in JavaScript

 November 1, 2018  Tanmay Sakpal  0 Comments arrays in javascript, javascript arrays


JavaScript arrays are used to store multiple values in a single variable. An array in
JavaScript can hold different elements We can store Numbers, Strings and Boolean in a
single array. Also arrays in JavaScript are dynamic in nature, which means its size can
increase or decrease at run time.

Syntax –
Use the following syntax to create an Array object −

1var fruits = [ "apple", "orange", "mango" ];


2var fruits = new Array( "apple", "orange", "mango" ); // another way but
not prefered

Access the Elements of an Array –


You access an array element by referring to the index number. This statement accesses the
value of the first element in cars:

1var cars = ["Saab", "Volvo", "BMW"];


2var name = cars[0];

Access the Full Array –


With JavaScript, the full array can be accessed by referring to the array name:

1var cars = ["Saab", "Volvo", "BMW"];
2document.write("<h2>"+cars[i]+"</h2>");

The length Property –


The length property of an array returns the length of an array (the number of array elements).

1var fruits = ["Banana", "Orange", "Apple", "Mango"];


2fruits.length;                       // the length of fruits is 4

Looping Array Elements –


The safest way to loop through an array, is using a “for” loop:

1var fruits, text, fLen, i;


2fruits = ["Banana", "Orange", "Apple", "Mango"];
3fLen = fruits.length;

5text = "<ul>";
6for (i = 0; i < fLen; i++) {
7    text += "<li>" + fruits[i] + "</li>";
8}
9text += "</ul>";

You might also like