× Introduction Setup Environment Building blocks Built-in functions Data Types Strings Operators Conditional statements Loop statements Functions Arrays Understaing Objects Date Object Number Object Math Object String Object Window Location Navigator History DOM Basics Forms
   Programs
Basic Control Loops Functions Arrays Examples Projects Quick Ref.
   Exercises
Variables Data Types Operators Decision Loops Reeborg's World



JavaScript Arrays

In this tutorial you will learn abount arrays, creating arrays and array methods.

Arrays

Arrays are lists of values. These values can be of all data types and one array can even contain different data types. It is often very useful to store multiple values inside one variable; for example, a list of students, groceries, or test scores.

Creating arrays:

The simplest way to create an array in JavaScript is enclosing a comma-separated list of values in square brackets ([]), as shown in the following

syntax:
 
let myArray = [element0, element1, ..., elementN];

Array can also be created using the Array() constructor as shown in the following syntax. However, for the sake of simplicity previous syntax is recommended.

syntax:
let myArray = new Array(element0, element1, ..., elementN);
Example:Try It
let fruits = ["Apple", "Orange", "Banana", "Orange"];

Accessing elements

We can access array elements by referencing the array's index. JavaScript assigns an index to every value of the array. The first value is assigned the position of 0, the second 1, the third 2, and so on. If we want to call a specific value based on its position in the array, we can use the name of our array, add square brackets to the end, and put the index we want to access between the square brackets.

Example: Try It
let fruits = ["Apple", "Orange", "Banana", "Orange"];
document.write(fruits [1]);  // writes Orange to the document.

Overwriting elements

The elements in an array can be overwritten. This can be done by accessing a certain element using the index and assigning a new value:

Example:Try It
let fruits = ["Apple", "Orange", "Banana", "Orange"];
fruits [1] = "Papaya";
document.write(cars[1]); // writes Papaya to the document.

Built-in length property

Arrays have a very useful built-in property: length. This will return the number of values that the array has:

Example: Try It
let colors = ["black", "orange", "pink"];
let fruits = ["Apple", "Orange", "Banana", "Orange"];

document.write("Length of colors:  " + colors.length); 
document.write("Length of fruits:  " + fruits.length); 

Note: The Array length is one higher than the maximum index because the index of the array starts at 0, but when determining the length, we look at the number of elements.

Use the length to access the last element of the array:

Example: Try It
lastElement = colors[colors.length - 1];

Nest one Array within Another Array

We can nest arrays within other arrays, like below:

Example: Try It
const students = [["Ravi", 7], ["Ajay", 8]];

This is also called a multi-dimensional array.


Looping Through Array Elements

We can use for loop, for-of and for-in loops to access each element of an array in sequential order.

Using for loop:

Example: Try It
let fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
 
// Iterates over array elements
for(let i = 0; i < fruits.length; i++) {    
    document.write(fruits[i] + "
"); // Print array element }

for of loop

There is another loop we can use to iterate over the elements of an array: the for of loop. It cannot be used to change the value associated with the index as we can do with the regular loop, but for processing values it is a very nice and readable loop.

Example: Try It
Here is what the syntax looks like:
let arr = [some array];
for (let variableName of arr) {
// code to be executed
}

var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
 
// Iterates over array elements
for(let fruit of fruits) {    
    document.write(fruit + "
"); // Print array element }

The for...in Loop

The for-in loop is a special type of a loop that iterates over the properties of an object, or the elements of an array. The for in loop is somewhat similar to the for of loop. Again here, we need to specify a temporary name, also referred to as a key, to store each property name in.

Example: Try It
 The generic syntax of the for-in loop is:
for(variable in array) {
    // Code to be executed
}

var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
 
// Loop through all the elements in the array 
for(let fruit in fruits) {  
    document.write(fruits[fruit] + "
"); }

Array methods

We have just seen the built-in length property. We also have a few built-in methods. Methods are functions on a certain object. Instead of holding a value, like properties, they perform actions.

Adding Elements:

We can add elements with the push() method.

Example: Try It
let fruits = ["Apple", "Banana", "Mango"];
fruits.push("Orange");

The value gets added to the end of the array. The push method returns the new length of the array. You can store this length in a variable like this:

Example:
let lengthOfFruits = fruits.push("Papaya");
document.write(fruits);
document.write(lengthOfFruits);

Deleting last element:

The pop() method deletes the last element of an array and returns the value popped off.

Example: Try It
let fruits = ["Apple", "Banana", "Mango"];
fruits.pop();
document.write(fruits);

The shift() and unshift() Methods.

The shift() method removes the first element of an array and returns the value shifted off; the unshift() method adds elements to the beginning of the array and returns the new length of the array. These methods are just like pop() and push() except that they manipulate the beginning of the array instead of the end of it.

Example: Try It
let fruits = ["Apple", "Banana", "Mango"];
fruits.shift();  // Removes the first element from an array
document.write(fruits); // Prints: Banana,Mango

fruits = ["Apple", "Banana", "Mango"];
fruits.unshift("Papaya","Grape");  // Adds Papaya, Grape to the front of the array
document.write(fruits); // Prints: Papaya,Grape,Apple,Banana,Mango

The slice() Method

The slice() method copies elements of one array into a new array. The slice() method takes two arguments: The first is the starting element in a range of elements that will be copied, and the second is the last element in the range, but this element is not included in what is copied. Remember that the index starts at zero, so that a beginning position of 2 is really element 3. The original array is unaffected unless you assign the result of the slice back to the original array.

Example: Try It
let fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
var sliceArray=names.fruits(2, 4);
document.write(fruits); // Prints: Mango,Orange

The splice() Method

The splice() method removes a specified number of elements from some starting position in an array and allows you to replace those items with new ones.

Syntax:Try It
Arrayname.splice(index position, number of elements to remove);
Arrayname.splice(index position, number of elements to remove,
replacement elements);

let colors = ["Red", "Green", "Yellow", "Blue"];
colors.splice(2, 0, "White", "Black");
document.write(colors); // Prints: Red,Green,White,Black,Yellow,Blue

colors.splice(2, 2); 
document.write(colors);  // Prints: Red,Green,Yellow,Blue

Sorting

There is also a built-in method for sorting arrays. It sorts numbers from small to high and strings A-Z. You can call sort() on an array and the order of the values of the array will change to a sorted order:

Example: Try It
let colors = ["Red", "Green", "Yellow", "Blue"];
colors.sort();
document.write(colors);  // Prints: Blue,Green,Red,Yellow

Reversing

The elements of the array can be reversed by calling the built-in method, reverse(), on an array. It puts the last element first, and the first element last. It does not matter whether the array is sorted or not; it just reverses the order.

Example: Try It
let colors = ["Red", "Green", "Yellow", "Blue"];
colors.reverse();
document.write(colors);  // Prints: Blue,Yellow,Green,Red

join

Javascript array join() method joins all the elements of an array into a string.

Syntax:
array.join(separator);

separator specifies a string to separate each element of the array. If omitted, the array elements are separated with a comma.

Example: Try It
let colors = ["Red", "Green", "Yellow", "Blue"];
let stringColours = colors.join("-");
document.write(colors);  // Prints: Red-Green-Yellow-Blue

lastIndexOf

Javascript array lastIndexOf() method returns the last index at which a given element can be found in the array, or -1 if it is not present. The array is searched backwards, starting at fromIndex.

Syntax:
array. lastIndexOf (searchElement, fromIndex);

searchElement is the Element to locate in the array. fromIndex is the index at which to start searching backwards. Defaults to the array's length, i.e., the whole array will be searched. If the index is greater than or equal to the length of the array, the whole array will be searched. If negative, it is taken as the offset from the end of the array.

Example: Try It
let colors = ["Red", "Green", "Yellow", "Blue", "White", "Yellow", "Black"];
let yellowLastIndex = colors.lastIndexOf("Yellow");
document.write(yellowLastIndex); // Prints:5
yellowLastIndex = colors.lastIndexOf("Yellow", 3);  // Prints:2

concat()

Javascript array concat() method returns a new array comprised of this array joined with two or more arrays.

Syntax:
array.concat(value1, value2, ..., valueN);

valueN is Arrays and/or values to concatenate to the resulting array.

Example: Try It
let colors = ["Red", "Green", "Yellow", "Blue"];
let fruits = ["Apple", "Banana", "Mango"];
let colorsFruits = colors.concat(fruits);
document.write(colorsFruits); //Prints: Red,Green,Yellow,Blue,Apple,Banana,Mango