Skip to main content

Array index

An array index is the position number of an element in the array. It lets you access, change, or remove the element you need.


Key facts

  • Indexing starts at zero (0). The first element has index 0, the second 1, the third 2, and so on.
  • An index is simply a numeric key of an array element.
  • An element is accessed through square brackets: array[index].

Example:

javascript
const fruits = ["apple", "banana", "cherry"]; console.log(fruits[0]); // "apple", the first element console.log(fruits[1]); // "banana", the second element console.log(fruits[2]); // "cherry", the third element

Changing an element by index:

javascript
fruits[1] = "orange"; console.log(fruits); // ["apple", "orange", "cherry"]

Array length and the last index

  • The .length property shows the number of elements.
  • The index of the last element always equals length - 1.
javascript
const numbers = [10, 20, 30, 40]; console.log(numbers.length); // 4 console.log(numbers[numbers.length - 1]); // 40

What if you access a nonexistent index?

javascript
console.log(fruits[10]); // undefined

In short:

ConceptDescription
Indexposition of an element in the array
First elementindex 0
Last elementindex length - 1
Nonexistent indexreturns undefined

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.