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 second1, the third2, 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 elementChanging an element by index:
javascript
fruits[1] = "orange";
console.log(fruits); // ["apple", "orange", "cherry"]Array length and the last index
- The
.lengthproperty 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]); // 40What if you access a nonexistent index?
javascript
console.log(fruits[10]); // undefinedIn short:
| Concept | Description |
|---|---|
| Index | position of an element in the array |
| First element | index 0 |
| Last element | index length - 1 |
| Nonexistent index | returns undefined |
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.