JavaScript Tutorial
JS - Introduction JS - Basic JS - Placement JS - Output JS - Statements JS - Syntax JS - Variables JS - Comments JS - Data Types JS - Operators JS - Operator Precedence JS - Condition JS - Switch JS - Functions JS - Objects JS - Loops For JS - Loops While JS - Break JS - Strings JS - String Methods JS - Numbers JS - Number Methods JS - Arrays JS - Array Methods JS - Array Iteration JS - Events JS - Event Listener JS - Event Propagation JS - Date JS - Math JS - Random JS - Boolean JS - Type Conversion JS - RegExp JS - Exception JS - Scope JS - Debugging JS - Hoisting JS - Strict Mode JS - this Keyword JS - Mistakes JS - Best Practices JS - Performance JS - Form Validation JS - ES6 Features
JS Objects
Object Definitions Object Properties Object Methods Object Constructors Object Prototypes
JS Functions
Function Definitions Function Parameters Function Call Function Apply Function Closures
JS HTML DOM
DOM Introduction DOM Methods DOM Selectors DOM HTML DOM CSS DOM Attributes DOM Navigation
JS Browser BOM
JS - Window JS - Screen JS - Location JS - History JS - Navigator JS - Popup Alert JS - Timing JS - Cookies
JS AJAX
AJAX - Introduction AJAX - XMLHttp AJAX - Request AJAX - Response AJAX - PHP
JS JSON
JSON - Introduction JSON - Syntax JSON - Data Types JSON - Parse JSON - Stringify JSON - Objects JSON - Arrays JSON - PHP JSON - JSONP
JS References
JavaScript Reference JavaScript Methods HTML DOM Reference

JavaScript Arrays

An array in JavaScript is a type of global object that is used to store multiple values in a single variable.

Arrays can contain any data type, including strings, numbers, objects, functions, and even other arrays.

Let's suppose you want to store the name of cities in your JavaScript code. Storing the city names one by one in a variable could look something like this:

But what happens if you need to store the city names of a country in variables and this time this not just three may be hundred.

Using so many variables simultaneously and keeping track of them all will be a very difficult task.

Arrays solve this problem by providing an ordered structure for storing multiple values or a group of values in a single variable.


Creating an Array

There are two ways to create an array in JavaScript:

  • The array literal, which uses square brackets: []
  • The array constructor, which uses the new keyword

Let's demonstrate how to create an array of fruits using the array literal, which is initialized with []:

Run code

Spaces and line breaks are not important. A declaration can span multiple lines:

Run code

Now here is the same data created with the array constructor, which is initialized with new Array():

Run code

Both methods will create an array. However, the array literal (square brackets) method is much more common and preferred, as the new Array() constructor method may have inconsistencies and unexpected results.


Indexing Arrays

Arrays do not have name/value pairs. Instead, they are indexed with integer values beginning with 0.

Here is an example array, assigned to fruits:

Here is a breakdown of how each element in the fruits array is indexed:

0 1 2 3
Apple Mango Banana Orange

The first element in the array is "Apple", which is indexed at 0.

The last element is "Orange", which is indexed at 3.


Accessing Elements in an Array

An element in a JavaScript array is accessed by referring to the index number of the element in square brackets.

Run code

JavaScript arrays are zero-indexed: the first element of an array is at index 0, the second is 1, and so on.

Attempting to access an element that doesn't exist will return undefined.

Run code

The full array can be accessed by referring to the array name.

Run code

The length Property

We can find out how many elements are in an array with the length property.

Run code

The last element is at the index equal to the value of the array's length property minus 1.

This example shows last element's value using length property:

Run code

Adding an Element to an Array

In our fruits variable we had four elements, which consisted of the indices from 0 to 3. If we want to add a new element to the array, we can assign a value to the next index.

Run code

If we add an element and accidentally skip an index, it will create undefined "holes" in the array.

Run code

Issues like that can be avoided by using the push() method, which adds an element to the end of an array.

Run code

New element can also be added to an array using the length property.

Run code

Modifying Elements in Arrays

We can overwrite any value in an array by assigning a new value using the assignment operator.

Run code

Arrays are often used to group together lists of similar data types, but they can technically contain any value or a mix of values.

Run code

Looping Through an Array

We can loop through the entirety of the array with the for loop, taking advantage of the length property.

In this example, we create an array of fruits and print out each index number as well as each value to the document:

Run code

We can also use the Array.forEach() method:

Run code

We can also use the for...of loop, a newer feature of JavaScript:

Run code

The for...of loop does not retrieve the index number of the elements in the array, but it is generally a simpler, more concise way to loop through an array.


Multi-dimensional Array

A multidimensional array is an array containing one or more arrays.

JavaScript understands multidimensional arrays that are two, three, four, five, or more levels deep. However, arrays more than three levels deep are hard to manage for most people.

The dimension of an array indicates the number of indices you need to select an element:

  • For a two-dimensional array you need two indices to select an element
  • For a three-dimensional array you need three indices to select an element

A two-dimensional array can be think as a table, where first [ ] is row and second [ ] is column.

Run code

In this example, we create a two-dimensional array and print out each index number as well as each value to the document:

Run code

You can get the size of rows and columns using length property:

Run code

Mostly 2 dimensions will suffice, though some places where you can use 3 dimensions are during 3D operations, physics calculations, etc.


JavaScript Arrays are Objects

In JavaScript Arrays are a special type of objects.

The typeof operator in JavaScript returns "object" for arrays.

Run code

Avoid new Array()

There is no need to use the array constructor new Array().

Instead you should use the array literal [] method which is much more common and preferred.

The following two different statements create a new empty array named scores:

The following two different statements create a new array containing 5 numbers:

Run code

The new Array() constructor method may have inconsistencies and can also produce some unexpected results:

Run code

How to Recognize an Array

As you know that the JavaScript typeof operator returns "object" for arrays.

A common question is: How do you know if a variable is an array?

To solve this problem ECMAScript 5 defines a new method Array.isArray():

Run code

You can also use the instanceof operator returns true if an object is created by a given constructor:

Run code

Passing Arrays to Functions

In the following example we will pass an array to a function:

Run code

Returning Arrays from Functions

In the following example we will return an array from a function:

Run code