Array Element Access in JavaScript

Introduction

Arrays store ordered values, but programs only become useful when you read and update elements reliably. This chapter covers zero-based indexing, negative indexes with at(), bounds behavior, and updating slots in place—skills you use in every list UI and data table.

Prerequisites

Zero-Based Indexing

The first element is index 0:

javascript
// Index positions
const colors = ["red", "green", "blue"];
 
console.log(colors[0]);
console.log(colors[1]);
console.log(colors[2]);

Negative Indexes with at()

Classic bracket syntax does not support negative indexes; at() does:

javascript
// Last and second-to-last items
const items = ["a", "b", "c", "d"];
 
console.log(items.at(-1));
console.log(items.at(-2));

Bracket style for last item (older pattern):

javascript
// length - 1 for last index
const last = items[items.length - 1];
console.log(last);

Reading Out of Range

javascript
// Undefined when index missing
const nums = [10, 20];
console.log(nums[5]);
console.log(nums.at(99));

Check length or use optional logic before access in production code.

Updating Elements

Arrays are mutable:

javascript
// Replace by index
const scores = [80, 75, 90];
scores[1] = 88;
console.log(scores);

Cannot assign past the end to “extend” reliably—use push (next chapter).

length Property

javascript
// length updates as array grows
const queue = ["job-1", "job-2"];
console.log(queue.length);
 
queue.push("job-3");
console.log(queue.length);

length is one greater than the last index.

Looping with Indexes

When you need position:

javascript
// Index + value
const names = ["Ada", "Lin", "Sam"];
 
for (let i = 0; i < names.length; i++) {
  console.log(`${i}: ${names[i]}`);
}

Prefer for...of when index is unnecessary.

Mini Example: Rotate Display Order

javascript
// Show last three items using negative at()
const history = ["v1", "v2", "v3", "v4", "v5"];
 
for (let offset = 1; offset <= 3; offset++) {
  console.log(history.at(-offset));
}

FAQ

Why start at 0?

Historical and mathematical convention in C-family languages including JavaScript.

Is arr[-1] valid?

In JavaScript, arr[-1] accesses a property named "-1", not the last element—use at(-1).

Can I store objects in arrays?

Yes—[{ id: 1 }, { id: 2 }] is common for API rows.

What comes next?

Array mutationpush, pop, splice, and more.