Javascript Data Structure Tutorial - Javascript Array








Javascript Array

An array is a linear collection of elements.

Array elements can be accessed via indices.

Array index is usually integer value used to compute offsets.

The first element in an array has the index of 0.

A JavaScript array is JavaScript object. Array indices are property names that can be integers used to represent offsets.

There is a set of properties and functions you can use with arrays.

For example, we can used buildin array functions such as shift, push to add elements to an array object.

In the following pages we will talk about the buildin function one by one with examples.

There are several different ways to create arrays, access array elements, and perform tasks such as searching and sorting the elements in an array.





Array Creation

One way to create an array is to declare an array variable using the [] operator:

var numbers = []; 

When creating an array in the code above, the array length is 0. You can get the length of an array by calling the built-in length property:

print(numbers.length); // displays 0 

We can create an array by declaring an array variable with a set of elements inside the [] operator:

var numbers = [1,2,3,4,5]; 
print(numbers.length);

The code above generates the following result.

You can also create an array by calling the Array constructor:

var numbers = new Array(); 
print(numbers.length); 

The code above generates the following result.

We can call the Array constructor with a set of elements as arguments to the constructor:

var numbers = new Array(1,2,3,4,5); 
print(numbers.length); 

The code above generates the following result.

Finally, we can create an array by calling the Array constructor with a single argument specifying the length of the array:

var numbers = new Array(10); 
print(numbers.length); 

The code above generates the following result.

JavaScript array elements do not all have to be of the same type:

var objects = [1, "Javascript", true, null]; 

We can verify that an object is an array by calling the Array.isArray() function. The following code shows how to do this.

var numbers = 3; 
var arr = [711,411,1776]; 
console.log(Array.isArray(number));
console.log(Array.isArray(arr));   

The code above generates the following result.