Arrays in JavaScript

Arrays in JavaScript


Previous articles have explained what primary data types are. So, we have a basic understanding of them. We will now move further to Arrays that are always a significant type in any language.

Since it is a modern language and we already know about the limitations of arrays, but, in this language the people that designed JavaScript decided not to have those limitations.


I believe you must be aware of what an array is.

Though, I try to define it in my own words:

An array is a special variable that can store multiple values under a single name (or place).

So, how can we declare an array in JavaScript. It can be done in either of two ways:

Arrays in JavaScript

And, another is:

Arrays in JavaScript

Here, we declared an array named "india" and it has 5 elements.

Generally, we prefer the second way to declare an array. Since the first is usually used when we already know the values.

And an array's value can be accessed by:

Arrays in JavaScript

As we know, an array is an index-type and it always starts from 0.

As in C# and Java, we have the same concept of accessing the length of an array as in the following:

Arrays in JavaScript

In other words a length property.

Adding Items to an Array

We have already added items to an array, but that was done during the definition of the array. What if, I want to add items after that?

Then, we have methods in JavaScript to do this.

Ironically, we have no limitation of the last value in an array. And, we can expand them as much as we want.

To do that, we use the Push() method.

It will add items to the end of the array.

Arrays in JavaScript

Before pushing, we have something like this:

Arrays in JavaScript

And now we have something like this

Arrays in JavaScript

What if, I want to add an element in first. We still have a method to do such things; it is unshift().

Arrays in JavaScript

And, we have something like this in our browser.

Arrays in JavaScript

Delete items from an Array

Contrary, we have two methods to delete items from an array.

Pop() for end-deletion and shift() for start-deletion of items in an array.

Arrays in JavaScript

And, we have missed our last item.

Arrays in JavaScript

And, if we use the shift() method then we have no "Sir Jadeja".

Let's try this:

Arrays in JavaScript


We can define an array in JavaScript in either of two ways.

The first is using big braces [-] and the second is using new Array().

For data insertion we have two methods, the push() and unshift() methods. Where, push() adds items to the end and unshift() adds items to the beginning.

Same with data deletion, we have the pop() and shift() methods.

For the number of items in array, we have a length property that returns the actual number of items in an array.

As you know, it can be frequently used in loops.

Up Next
    Ebook Download
    View all
    View all