Accessing Array Items
Read and change items by their index.
Syntax
arr[index]
arr[index] = newValueAccess an item by its index in square brackets. Indexes start at 0, so the first item is arr[0].
Changing items
Assign to an index to replace an item. The last item is at arr[arr.length - 1].
Example
Loading editor…
Press Run to execute the code.
When to use it
- Read the first item in a sorted results array to display the top-ranked result prominently.
- Access the last element of a log array to show the most recent event without knowing its length.
- Iterate over form field references stored in an array using an index-based loop.
More examples
Zero-based index access
Accesses array elements by index, showing that out-of-bounds access returns undefined.
const colors = ["red", "green", "blue"];
console.log(colors[0]); // "red"
console.log(colors[2]); // "blue"
console.log(colors[5]); // undefined – out of boundsAccess last element
Shows two ways to access the last element: classic length-1 indexing and the modern at(-1) method.
const logs = ["start", "loading", "ready", "error"];
const last = logs[logs.length - 1];
const lastAlt = logs.at(-1); // ES2022
console.log(last, lastAlt); // "error" "error"Loop through with index
Uses a for-loop with an index variable to access and label each element in a scores array.
const scores = [88, 92, 74, 95];
for (let i = 0; i < scores.length; i++) {
console.log(`Score ${i + 1}: ${scores[i]}`);
}
Discussion