JavaScript Arrays

JavaScript arrays are used to store multiple values in a single variable.

Example

var cars = ["Saab", "Volvo", "BMW"];

Try It Yourself

What is an array?

An array is a special variable that can store more than one value at a time.

If you have a list of items (such as, a list of car brands), storing car brands in a single variable should be like this:

var car1 = "Saab";
var car2 = "Volvo";
var car3 = "BMW"; 

But, what if you want to iterate through all cars and find a specific value? What if it's not three car brands but three hundred?

The solution is an array!

An array can store many values in a single name, and you can also access these values by referencing the index number.

Create an array

Using array literals is the simplest method to create a JavaScript array.

Syntax:

var array-name = [item1, item2, ...];

Example

var cars = ["Saab", "Volvo", "BMW"];

Try It Yourself

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

Example

var cars = [
    "Saab",
    "Volvo",
    "BMW"
];

Try It Yourself

Do not write a comma after the last element (e.g., "BMW",).

There may be cross-browser compatibility issues.

Using the JavaScript keyword new

The following example will also create an array and assign values to it:

Example

var cars = new Array("Saab", "Volvo", "BMW");

Try It Yourself

The effects of the above two examples are completely the same. There is no need to use new Array().

For simplicity, readability, and execution speed, please use the first method (array literal method).

Access array elements

We access array elements by referencingIndex number (subscript)to refer to a specific array element.

This statement accesses the value of the first element in the cars array:

var name = cars[0];

This statement modifies the first element in the cars array:

cars[0] = "Opel";

Example

var cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars[0]; 

Try It Yourself

[0] is the first element in the array. [1] is the second. Array indexing starts from 0.

Change array element

This statement modifies the value of the first element in the cars array:

cars[0] = "Opel";

Example

var cars = ["Saab", "Volvo", "BMW"];
cars[0] = "Opel";
document.getElementById("demo").innerHTML = cars[0];

Try It Yourself

Access the entire array

Through JavaScript, you can access the entire array by referencing the array name:

Example

var cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars; 

Try It Yourself

Arrays are objects

Arrays are a special type of object. In JavaScript, arrays are used typeof The operator will return "object".

However, it is best to describe JavaScript arrays as arrays.

Array usagenumbersto access its "elements". In this example,person[0] Return Bill:

Array:

var person = ["Bill", "Gates", 62];

Try It Yourself

Objects useNameto access its "members". In this example,person.firstName Return Bill:

Object:

var person = {firstName:"Bill", lastName:"Gates", age:19};

Try It Yourself

Array elements can be objects

JavaScript variables can be objects. Arrays are a special type of object.

Therefore, you can store different types of variables in the same array.

You can store objects in an array. You can also store functions in an array. You can even store arrays in an array:

myArray[0] = Date.now;
myArray[1] = myFunction;
myArray[2] = myCars;

Array properties and methods

The real power of JavaScript arrays is hidden in the properties and methods of arrays:

Example

var x = cars.length;   // The length property returns the number of elements
var y = cars.sort();   // The sort() method sorts the array

We will learn array methods in the next chapter.

length property

length The property returns the length of the array (the number of array elements).

Example

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.length;                       // The length of fruits is 4

Try It Yourself

length The property is always greater than the highest array index (index).

Access the first array element

Example

fruits = ["Banana", "Orange", "Apple", "Mango"];
var first = fruits[0];

Try It Yourself

Access the last array element

Example

fruits = ["Banana", "Orange", "Apple", "Mango"];
var last = fruits[fruits.length - 1];

Try It Yourself

Iterate over array elements

The safest way to iterate over an array is to use "for"Loop:"

Example

var fruits, text, fLen, i;
fruits = ["Banana", "Orange", "Apple", "Mango"];
fLen = fruits.length;
text = "<ul>";
for (i = 0; i < fLen; i++) {
     text += "<li>" + fruits[i] + "</li>";
} 

Try It Yourself

You can also use Array.forEach() Function:

Example

var fruits, text;
fruits = ["Banana", "Orange", "Apple", "Mango"];
text = "<ul>";
fruits.forEach(myFunction);
text += "</ul>";
function myFunction(value) {
  text += "<li>" + value + "</li>";
}

Try It Yourself

Adding array elements

The best way to add an array element is to use push() Method:

Example

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Lemon");                // Add a new element (Lemon) to fruits

Try It Yourself

or length To add a new element to an array, you can use the

Example

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[fruits.length] = "Lemon";     // Add a new element (Lemon) to fruits

Try It Yourself

Warning!

Adding an element at the highest index can create undefined "holes" in the array:

Example

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[6] = "Lemon";                 // Add a new element (Lemon) to fruits

Try It Yourself

Associative Arrays

Many programming elements support associative arrays with named indices.

Arrays with named indices are called associative arrays (or hashes).

in JavaScript. Named index arrays are not supportedarrays with named indices.

In JavaScript, arrays can only usenumeric indices.

Example

var person = [];
person[0] = "Bill";
person[1] = "Gates";
person[2] = 62;
var x = person.length;          // person.length returns 3
var y = person[0];              // person[0] returns "Bill"

Try It Yourself

Warning!

If you use named indices, JavaScript will redefine the array as an object.

After that, all the methods and properties of the array will produce incorrect results.

Example:

var person = [];
person["firstName"] = "Bill";
person["lastName"] = "Gates";
person["age"] = 62;
var x = person.length;         // person.length will return 0
var y = person[0];              // person[0] will return undefined

Try It Yourself

The difference between arrays and objects

In JavaScript,ArrayUsenumeric indices.

In JavaScript,objectsUseNamed indices.

Arrays are a special type of object that have numeric indices.

When to use an array and when to use an object?

  • JavaScript does not support associative arrays
  • If you want the element names to bestrings (text)then you should useobjects.
  • If you want the element names to benumbersthen you should useArray.

Avoid new Array()

There is no need to use JavaScript's built-in array constructor new Array().

Please use [] Instead!

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

var points = new Array();         // Bad
var points = [];                  // Good

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

var points = new Array(40, 100, 1, 5, 25, 10); // Bad
var points = [40, 100, 1, 5, 25, 10];          // Good

Try It Yourself

new Keywords can only complicate the code. They can also produce some unexpected results:

var points = new Array(40, 100);  // Creates an array with two elements (40 and 100)

What if we delete one of the elements?

var points = new Array(40);       // Creates an array with 40 undefined elements!!!

Try It Yourself

How to identify an array

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

The problem lies with JavaScript operators typeof Returns "object:

var fruits = ["Banana", "Orange", "Apple", "Mango"];
typeof fruits;             // Returns object

Try It Yourself

The typeof operator returns "object" because JavaScript arrays are objects.

Solution 1:

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

Array.isArray(fruits);     // Returns true

Try It Yourself

The problem with this solution is ECMAScript 5 Not supported in old browsers.

Solution 2:

Create your own isArray() The function solves this problem:

function isArray(x) {
    return x.constructor.toString().indexOf("Array") > -1;
}

Try It Yourself

If the argument is an array, then the above function always returns true.

Or a more accurate explanation is: If the object prototype contains the word "Array", then return true.

Solution 3:

If the object is created by the given constructor, then instanceof Operator returns true:

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits instanceof Array     // Returns true

Try It Yourself