JavaScript - Arrays

October 2017

Javascript variables are used to store a single data (at a given time). However, since it is often required to manipulate large amounts of data, this concept shows its limitations, as it is difficult to manage a large number of distinct variables.
  • To remedy this Javascript provides a data structure for storing data in a "common variable": the array
  • A Javascript array, is a variable that can contain multiple independent data indexed by a number, called index. The index of an array is thus used to access data stored therein.

Multidimensional Arrays

When the array is composed only of variables, is called a mono-dimensional array . Here's a way to represent it:

Datadata 1data 2data 3data 4
  • The first element in an array always has an index of 0.
  • In an array of n elements, the nth element has the n-1 index.

When a array contains other arrays is referred to as a multidimensional arrays. Here is a representation of a multidimensional array:

data 1
data 2 (array)
data 1data 2data 3
data 3
data 4 (tableau)
data 1data 2

Associative arrays

It is possible to make use of a custom index to identify and define each value, it is called an associative array. Javascript indeed allows the use of a string or a specific number to index the values of an array??. Here is a sample representation of an associative array:

Creating an array

Javascript provides several ways to create a table:

var MyArray = ["data 1", "data  2", "data  3", "data  4"];
var MyArray = new Array("data  1", "data  2", "data  3", "data  4");

The array is initialized with the above value. It should be noted that n array must be declared before it is assigned values??.

The declaration of an array is as follows:

var MyArray = new Array();

How to access the data?

Access to the elements of an array is done by writing the name of the array followed by brackets containing the index of the element.

var MyArray = ["Teebo",

document.write("The 4th element of the array is "+MyArray[3]);

// Display  "The 4th element of the array is Kalamit"

Assigning values

To create an associative array, you have to declare an array variable, then write the name of the array, followed by a name (index) between brackets and assign the data usng assignment operator:

MyArray[0] = "Bonjour";
MyArray["Pierre"] = 12;
MyArray["Jean-François"] = 25;

Working with tables

Javascript offers the Array object with many methods for manipulating arrays: Javascript - The Array object

Original document published on
Published by jak58. Latest update on May 20, 2013 at 11:38 AM by jak58.
This document, titled "JavaScript - Arrays," is available under the Creative Commons license. Any copy, reuse, or modification of the content should be sufficiently credited to CCM (