Skip to main content

JavaScript Arrays

JavaScript Array Access

Written by Published

JavaScript array elements are read using their index, starting at 0.

The first element is at index 0, not 1.

This catches out almost everyone at first, so it is worth saying twice.

Example

Example

javascript

const fruits = ["Apple", "Banana", "Mango"];

console.log(fruits[0]);
console.log(fruits[2]);

The output is Apple then Mango.

How Indexes Work

An index is the position of an element, counted from 0.

Write the index in square brackets after the array name.

Reading an index that does not exist gives undefined rather than an error.

Syntax

Syntax

javascript

array[index]

The index must be a number, not a name in quotes.

The Last Element

Because counting starts at 0, the last index is length - 1.

Example

Example

javascript

const fruits = ["Apple", "Banana", "Mango"];

console.log(fruits[fruits.length - 1]);

The output is Mango.

Using at()

at() does the same job and accepts negative numbers.

at(-1) is a much clearer way to ask for the last element.

Example

Example

javascript

const fruits = ["Apple", "Banana", "Mango"];

console.log(fruits.at(-1));
console.log(fruits.at(0));

Negative numbers count backwards from the end.

An Index That Does Not Exist

Reading past the end is not an error, which can hide bugs.

Example

Example

javascript

const fruits = ["Apple"];

console.log(typeof fruits[5]);

The output is undefined.

Changing an Element

Assign to an index to replace the value there.

Example

Example

javascript

const fruits = ["Apple", "Banana"];

fruits[1] = "Cherry";

console.log(fruits.join(","));

The second element has been replaced.

Reading Nested Arrays

Use one pair of brackets for each level.

Example

Example

javascript

const grid = [[1, 2], [3, 4]];

console.log(grid[1][0]);

The first bracket picks the row, the second picks the value in it.

Complete Example

Complete Example

html

<!DOCTYPE html>
<html>
<head>
  <title>JavaScript Array Access</title>
</head>
<body>

  <h1>JavaScript Array Access</h1>

  <p id="result"></p>

  <script>
    const fruits = ["Apple", "Banana", "Mango"];

    document.getElementById("result").innerHTML =
      "First: " + fruits[0] + "<br>Last: " + fruits.at(-1);
  </script>

</body>
</html>

Try It Yourself

Run the above example in the Try It Editor.

Try a middle element:

Show fruits[1] as well and see which name appears.

Important Points

  • Indexes start at 0.
  • The last index is length - 1.
  • at(-1) reads the last element directly.
  • Reading a missing index gives undefined, not an error.
  • Assigning to an index replaces the value there.

Conclusion

JavaScript array access uses a numeric index that starts at 0.

at() makes reading from the end far more readable.

Understanding indexes is needed for every loop over an array.