JavaScript Arrays

Last Updated Jul 29, 2015, 07:00:14 PM

JavaScript Arrays

Arrays provide a way to store multiple pieces of information in a single thing. An array is basically a list of values: numbers, strings, boolean values or even other arrays.

An array is what's called a data structure; in other words, it's a way to store and organize information.

See the image below for more understanding of JavaScript Arrays

Understand more about arrays

Create an Array

Try It Now

The above example will find the length of the array elements. Each country name is considered as an element in array.


Create an Array using new keyword

You can create javascript arrays in two ways with and without using new keyword

Try It Now

Access Array Elements

You can actually access any element in the array using its index. Index is the array element position. Index typically starts with 0

The above example code will access the third element of the array, not the second element as I said the index will start from 0 not from 1

Try It Now

Create Array in Different Ways

You can actually create the javascript arrays in two ways like below

Both the declarations are same. But technically there is a difference.

Using the most verbose method: new Array() does have one extra option in the parameters: if you pass a number to the constructor, you will get an array of that length:

Try It Now

You're telling the interpreter, I want to call the constructor "Array" and generate an object. It then looks up through your execution context to find the constructor to call, and calls it, creating your array.

When you use this, you're telling the interpreter to create a new runtime array. No extra processing necessary at all.

Try It Now

In the above example, the first call will alert 'SPORT' as you'd expect. The second will not. You will end up seeing undefined. You'll also note that b contains all of the native Array object functions such as 'push', where the other does not.

While you may expect this to happen, it just illustrates the fact that '[]' is not the same as 'new Array()'.

It's probably best to just use [] if you know you just want an array. I also do not suggest going around and redefining Array...

Sources and Credits

The source of the content has been referred and updated with Mozilla Developer Network and W3C Organization

Last Updated Jul 29, 2015, 07:00:14 PM

Browser compatibility

Basic support Yes Yes Yes Yes Yes Yes Yes