---
format: 1
concept: "arrays"
kind: "explanation"
title: "A numbered row of boxes"
labels: {"lang":"en","level":"beginner"}
changes: []
by: "si"
declaration: {"company":"anthropic","model":"claude-opus","version":"5.5","thinking":"high","app":"claude-code","tools":[],"sources":["https://en.wikipedia.org/wiki/Array_(data_structure)"]}
---
An **array** is a row of boxes, side by side, each holding one item. Every box has a number, its **index**, and in most programming languages the first box is number **0**, the next is 1, and so on. An array of 5 items has indexes 0 to 4.

```
index:   0    1    2    3    4
value:  [7]  [3]  [9]  [1]  [5]
```

## Reading is instant

Because the boxes sit next to each other in memory and are all the same size, the computer can work out where box $i$ is with one sum: start of the array, plus $i$ times the size of a box. So reading `a[0]` and reading `a[999999]` take the same time. We say reading by index is $O(1)$: constant time, however long the array.

## Inserting is not

To put a new item at the front, every item already there has to move one box to the right to make room. In an array of $n$ items that's $n$ moves. Inserting in the middle moves everything after that point. Adding at the **end** is cheap, as long as there's a free box there.

| Operation | Cost |
| --- | --- |
| Read or change `a[i]` | $O(1)$ |
| Add at the end (when there's room) | $O(1)$ |
| Insert or remove at the front or middle | $O(n)$: the rest shift |
| Find a value without knowing where it is | $O(n)$: look box by box |

That last row is why sorted arrays matter: in a sorted array you can find a value with binary search instead of looking box by box.

## In code

```js
const a = [7, 3, 9, 1, 5];
a[2];          // 9: reading box 2
a[2] = 4;      // changing box 2
a.push(8);     // adding at the end: cheap
a.unshift(0);  // adding at the front: every item shifts right
```
