Array in javascript

Array is most important keyword used in programming languages. Like other languages, Array is also used in javascript. Array in JavaScript is used to store multiple values in a single variable. Arrays in javascript is as special type of object. We can have variables of different types in the same Array. It may be object, function and array also.

Creating Array in javascript:

Syntax :
These are different types of syntax used to create array.

element0, element1, …, elementN :
A JavaScript array is initialized with the given elements.
arrayLength :
If the only argument passed to the Array constructor is an integer then it returns a new JavaScript array with length set to that number.
Note : Integer Number should be in range of between 0 and 2^32-1 (inclusive).
If the argument is any other number, a RangeError exception is thrown.


It creates arr name array object.

It creates fruits named array object without any element means empty array object

It creates fruits named array object with three elements.

We can use any of the above given method to create an array in javascript.

Accessing array elements
JavaScript arrays are zero-indexed: the first element of an array is at index 0, and the last element is at the index equal to the array’s length minus 1.
we use ordinal numbers to access an array as follows:

Setting array elements
we use ordinal numbers to set a value inside an array as follows:

Array.length property can be used for adding an element in last of an array object like above.
In above given example we set 4th element in fruits object but what will be happend if we add element at 6th element.

When setting a value on a JavaScript array when the value is a valid array index and that index is outside the current bounds of the array, the engine will update the array’s length property accordingly.

Array is object
Why Array is special type of object?
1. We can have variables of different types in the same Array. It may be object, function and array also.

2. The typeof operator in JavaScript returns “object” for arrays but it’s elements can be accessed or assigned by using only numbers like:

3. But can not be accessed like objects

4. javascript array does not support Associated array (Named index array).
Associate Array : key – value pairs which has name as index.

Even we can define it like

But can not be accessed using index number like
will return undefined and vehicle1.length will return 0.
so if we want to define associated array in javascript then use object.

You Might Interested In

Leave a Reply

Enclose a code block like: <pre><code>Your Code Snippet</code></pre>.