JavaScript Arrays

In this lession we will see how arrays work in JavaScript. Like any other languages, JavaScript also supports array types. Array type can hold same type or different type of the variables so we can also say that an Array is a list of varialbes.

In below code we will see how to define an array in JavaScript. We can define an array in two ways. First we can use brackets which is a standard notation for defining an array.

var months = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];

Other way is to define an array using it's constructor as below

var months = new Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12);

Accessing an element from Array

We can use the index of an element to access the specific element from an array. We need to pass index into brackets[]. Accessing element is zero-based indices, so if we want to get the first element we need to pass 0 index to the brackets. So for an example if we want to access 1 value from months array (in above example) we can access it using months[0]

console.log(months[0]);	// will print 1 on the console

JavaScript arrays are little different because it is not necessary to assign value to all the element in an array. We can assign value to some specific element and other element can be left undefined.

var statuses = [];
statuses[1] = "Done";
console.log(statuses);	// Will print like this [undefined, "Done"]

Different types of elements in array

As I have mentioned earlier that an array can hold various types of element in single array, we can say it's a special kind of an object. Means that we can have 1 element of integer type, 1 element of string type, 1 element of deciaml type and so on. We will define 1 array which will hold different different types of the values in the same array.

var mixArray = [];
mixArray[0] = 400;
mixArray[1] = "I am string";
mixArray[2] = "45.85";
mixArray[3] = false;

//Let's print values of above array by looping through it's all elements, please make 
//a note that we can get length of an array using .length property of an array.

for(var loop = 0; loop < mixArray.length; loop++)

//above code will print output as below
//I am string


← Previous

Next →