# Array Fundamentals

Course: [JavaScript](https://www.devtutorials.ai/learn/javascript) · Section: Arrays
Source: https://www.devtutorials.ai/learn/javascript/arrays/array-fundamentals

> Creating arrays and reading items by index, push, pop, unshift and shift, slice versus splice, copying with spread, changing a list without changing the original with map, filter, with and toSpliced, combining with concat, and flattening with flat and flatMap.

## What Is an Array?

**Array** = an ordered list of values, kept under one name.

- Written in square brackets: `["Pen", "Notebook", "Bag"]`.
- Each item has a position called an **index**, starting at `0`.
- `length` tells you how many items there are.

**Simple lesson:** an array is a numbered row of boxes. Box 0 is the first one.

### A Real-World Example

A customer adds a pen, a notebook and a bag to the cart.
The shop keeps them in one array, `cart`, instead of three variables.
Adding an item is `cart.push(...)`. Removing one makes a new list without it.

<figure className="ts-fig">
  <svg viewBox="0 0 560 170" role="img" aria-label="Three boxes in a row, indexes 0, 1 and 2, hold Pen, Notebook and Bag. A fourth box, Mug, slides in at index 3 and the length changes from 3 to 4." width="100%">
    <rect x="0" y="0" width="560" height="170" rx="12" fill="#f8fafc" stroke="#e2e8f0" />
    <rect x="40" y="50" width="100" height="50" rx="8" fill="#eff6ff" stroke="#2563eb" />
    <text x="90" y="80" textAnchor="middle" fontSize="13" fill="#1e40af">"Pen"</text>
    <text x="90" y="120" textAnchor="middle" fontSize="12" fill="#475569">0</text>
    <rect x="150" y="50" width="100" height="50" rx="8" fill="#eff6ff" stroke="#2563eb" />
    <text x="200" y="80" textAnchor="middle" fontSize="13" fill="#1e40af">"Notebook"</text>
    <text x="200" y="120" textAnchor="middle" fontSize="12" fill="#475569">1</text>
    <rect x="260" y="50" width="100" height="50" rx="8" fill="#eff6ff" stroke="#2563eb" />
    <text x="310" y="80" textAnchor="middle" fontSize="13" fill="#1e40af">"Bag"</text>
    <text x="310" y="120" textAnchor="middle" fontSize="12" fill="#475569">2</text>
    <g>
      <animateTransform attributeName="transform" type="translate" values="140,0;0,0;0,0" keyTimes="0;0.4;1" dur="3s" repeatCount="indefinite" />
      <rect x="370" y="50" width="100" height="50" rx="8" fill="#f0fdf4" stroke="#16a34a" />
      <text x="420" y="80" textAnchor="middle" fontSize="13" fill="#166534">"Mug"</text>
      <text x="420" y="120" textAnchor="middle" fontSize="12" fill="#475569">3</text>
    </g>
    <text x="280" y="155" textAnchor="middle" fontSize="12" fill="#475569">cart.push("Mug"): length 3 → 4</text>
  </svg>
  <figcaption>Indexes start at 0. push() adds a box at the end.</figcaption>
</figure>

## What You Will Learn

1. How to create an array and read its items.
2. How to add and remove items at the ends.
3. `slice()` and `splice()`, and copying arrays.
4. Changing a list **without** changing the original.
5. Combining and flattening arrays.

## Array basics

```js runnable title="A cart with three items"
const cart = ["Pen", "Notebook", "Bag"];
console.log(cart);
console.log(cart.length);
console.log(cart[0], cart[2]);
```

Expected output:

```text
[
  "Pen",
  "Notebook",
  "Bag"
]
3
Pen Bag
```

### Creating arrays

- `[]` makes an empty array. `["a", "b"]` makes one with items.
- `Array.from({ length: 3 }, (_, i) => i + 1)` builds `[1, 2, 3]` from a function.
- `typeof` says `"object"` for arrays, so check with `Array.isArray(value)`.

```js runnable title="Two ways to start an array"
const empty = [];
const prices = [20, 60, 799];
console.log(empty.length, prices.length);
empty.push("first");
console.log(empty.join(", "));
console.log(Array.from({ length: 3 }, (_, i) => i + 1).join(", "));
console.log(Array.isArray(prices), typeof prices);
```

Expected output:

```text
0 3
first
1, 2, 3
true object
```

### Reading elements

- `cart[0]` is the first item. `cart[cart.length - 1]` is the last.
- `cart.at(-1)` also gives the last item.
- A missing index gives `undefined`, not an error.

```js runnable title="Reading the first, the last and a missing element"
const cart = ["Pen", "Notebook", "Bag"];
console.log(cart[0]);
console.log(cart.at(-1));
console.log(cart[5]);
```

Expected output:

```text
Pen
Bag
undefined
```

### Adding and removing items

| Method | Does | End |
|---|---|---|
| `push(x)` | Adds | Back |
| `pop()` | Removes and returns | Back |
| `unshift(x)` | Adds | Front |
| `shift()` | Removes and returns | Front |

These four **change** the array itself.

```js runnable title="push, pop, unshift and shift on a queue of orders"
const queue = ["#101", "#102"];
console.log(queue.push("#103"));
console.log(queue);
console.log(queue.shift());
queue.unshift("#100");
console.log(queue.pop());
console.log(queue);
```

Expected output:

```text
3
[
  "#101",
  "#102",
  "#103"
]
#101
#103
[
  "#100",
  "#102"
]
```

`push()` returns the **new length**, not the array.

## Array modification

### slice()

`slice(start, end)` **copies** a part. The end index is not included. The original stays the same.

```js runnable title="slice() copies a section and leaves the original alone"
const items = ["Pen", "Notebook", "Bag", "Mug"];
const middle = items.slice(1, 3);
console.log(middle.join(", "));
console.log(items.join(", "));
```

Expected output:

```text
Notebook, Bag
Pen, Notebook, Bag, Mug
```

### splice()

`splice(start, deleteCount, ...newItems)` removes, inserts or replaces **in place**. It changes the original.

```js runnable title="splice() removes, inserts and replaces in place"
const items = ["Pen", "Notebook", "Bag", "Mug"];
const removed = items.splice(1, 1);
console.log(removed.join(", "), "|", items.join(", "));
items.splice(1, 0, "Ruler");
console.log(items.join(", "));
items.splice(2, 1, "Lunch box");
console.log(items.join(", "));
```

Expected output:

```text
Notebook | Pen, Bag, Mug
Pen, Ruler, Bag, Mug
Pen, Ruler, Lunch box, Mug
```

**slice** = copy a piece. **splice** = cut the array itself.

### Copying arrays

`const b = a` does **not** copy. Both names point to the same array. Use `[...a]` to copy.

```js runnable title="Assignment shares the array, spread copies it"
const cart = ["Pen"];
const shared = cart;
const copy = [...cart];
shared.push("Bag");
console.log(cart.join(", "));
console.log(copy.join(", "));
```

Expected output:

```text
Pen, Bag
Pen
```

### Updating arrays without changing the original

Pages and apps often keep the old list and build a new one. Two common ways:

#### Using `map()`

`map()` makes a new array with every item changed by your function.

```js runnable title="Raising one price with map()"
const products = [
  { name: "Pen", price: 20 },
  { name: "Bag", price: 799 },
];
const updated = products.map((p) => (p.name === "Pen" ? { ...p, price: 25 } : p));
console.log(updated.map((p) => `${p.name} ₹${p.price}`).join(", "));
console.log(products[0].price);
```

Expected output:

```text
Pen ₹25, Bag ₹799
20
```

#### Using the spread operator

Copy the parts before and after, and put the new item in the middle.

```js runnable title="Replacing one element with slice() and spread"
const sizes = ["S", "M", "L"];
const i = 1;
const changed = [...sizes.slice(0, i), "XL", ...sizes.slice(i + 1)];
console.log(changed.join(", "));
console.log(sizes.with(i, "XL").join(", "));
console.log(sizes.join(", "));
```

Expected output:

```text
S, XL, L
S, XL, L
S, M, L
```

`with(index, value)` does the same in one call: a copy with one item replaced.

## Adding items without changing the original

### Using the spread operator

```js runnable title="A new array with an item added at each end"
const cart = ["Pen", "Bag"];
const withMug = [...cart, "Mug"];
const withGift = ["Gift card", ...cart];
console.log(withMug.join(", "));
console.log(withGift.join(", "));
console.log(cart.join(", "));
```

Expected output:

```text
Pen, Bag, Mug
Gift card, Pen, Bag
Pen, Bag
```

### Using `concat()`

`concat()` returns a new array with the extra items at the end.

```js runnable title="concat() adds items and returns a new array"
const cart = ["Pen", "Bag"];
const bigger = cart.concat("Mug", "Ruler");
console.log(bigger.join(", "));
console.log(cart.length);
```

Expected output:

```text
Pen, Bag, Mug, Ruler
2
```

## Removing items without changing the original

### Using `filter()`

`filter()` keeps the items for which your function returns `true`.

```js runnable title="Removing one item, and removing every sold-out item"
const products = [
  { name: "Pen", stock: 10 },
  { name: "Bag", stock: 0 },
  { name: "Mug", stock: 4 },
];
const withoutPen = products.filter((p) => p.name !== "Pen");
const inStock = products.filter((p) => p.stock > 0);
console.log(withoutPen.map((p) => p.name).join(", "));
console.log(inStock.map((p) => p.name).join(", "));
console.log(products.length);
```

Expected output:

```text
Bag, Mug
Pen, Mug
3
```

### Using `slice()` and the spread operator

To remove by position, join the part before and the part after.

```js runnable title="Removing the element at index 2"
const items = ["Pen", "Notebook", "Bag", "Mug"];
const i = 2;
const result = [...items.slice(0, i), ...items.slice(i + 1)];
console.log(result.join(", "));
console.log(items.toSpliced(i, 1).join(", "));
console.log(items.join(", "));
```

Expected output:

```text
Pen, Notebook, Mug
Pen, Notebook, Mug
Pen, Notebook, Bag, Mug
```

`toSpliced()` works like `splice()`, but returns a changed copy and leaves the original alone.

## Combining arrays

### Using `concat()`

```js runnable title="Merging three lists with concat()"
const stationery = ["Pen", "Ruler"];
const bags = ["School bag"];
const bottles = ["Steel bottle"];
console.log(stationery.concat(bags, bottles).join(", "));
```

Expected output:

```text
Pen, Ruler, School bag, Steel bottle
```

### Using the spread operator

Spread lets you add single values between the lists, too.

```js runnable title="Merging lists with spread, and adding a value between them"
const morning = ["#101", "#102"];
const evening = ["#201"];
console.log([...morning, "--- lunch ---", ...evening].join(", "));
```

Expected output:

```text
#101, #102, --- lunch ---, #201
```

## Flattening arrays

**Nested array** = an array inside an array. **Flatten** = pull the inner items out into one list.

### Using `flat()`

`flat()` removes one level. `flat(2)` removes two. `flat(Infinity)` removes all.

```js runnable title="One level, two levels and every level"
const nested = ["Pen", ["Bag", ["Mug", ["Cup"]]]];
console.log(JSON.stringify(nested.flat()));
console.log(JSON.stringify(nested.flat(2)));
console.log(JSON.stringify(nested.flat(Infinity)));
```

Expected output:

```text
["Pen","Bag",["Mug",["Cup"]]]
["Pen","Bag","Mug",["Cup"]]
["Pen","Bag","Mug","Cup"]
```

### Using `flatMap()`

`flatMap()` = `map()` then `flat()`. Great for "every item from every order".

```js runnable title="Every item from every order, in one list"
const orders = [
  { id: 1, items: ["Pen", "Ruler"] },
  { id: 2, items: [] },
  { id: 3, items: ["Bag"] },
];
console.log(orders.flatMap((o) => o.items).join(", "));
```

Expected output:

```text
Pen, Ruler, Bag
```

## Arrays on a Web Page

The cart is an array. **Add** uses spread to make a new array, **remove** uses `filter()`, and the page is redrawn from the array each time.

```js runnable preview="cart" title="A cart page driven by one array"
const shop = [
  { id: 1, name: "Notebook", price: 60 },
  { id: 2, name: "Steel bottle", price: 299 },
  { id: 3, name: "Pencil box", price: 120 },
];
let cart = [];

function draw() {
  const cartList = document.querySelector("#cart");
  cartList.innerHTML = "";
  for (const item of cart) {
    const li = document.createElement("li");
    li.textContent = `${item.name} — ₹${item.price} `;
    const remove = document.createElement("button");
    remove.textContent = "Remove";
    remove.className = "ghost";
    remove.addEventListener("click", () => {
      cart = cart.filter((c) => c !== item);
      draw();
    });
    li.append(remove);
    cartList.append(li);
  }
  let total = 0;
  for (const item of cart) total += item.price;
  document.querySelector("#total").textContent = `₹${total}`;
  console.log("cart:", cart.map((c) => c.name).join(", ") || "(empty)");
}

for (const product of shop) {
  const li = document.createElement("li");
  const add = document.createElement("button");
  add.textContent = `Add ${product.name}`;
  add.addEventListener("click", () => {
    cart = [...cart, product];
    draw();
  });
  li.append(add);
  document.querySelector("#shop").append(li);
}

document.querySelector("#clear").addEventListener("click", () => {
  cart = [];
  draw();
});
draw();
```

Add a few items, remove one, then press **Empty cart**. The Console prints the array after each change.

**Easy way to remember:** `push`, `pop`, `shift`, `unshift` and `splice` **change** the array. `slice`, `concat`, `map`, `filter`, `flat` and spread make a **new** one.

## TL;DR

- Arrays are ordered lists. Indexes start at `0`; `at(-1)` is the last item.
- `push`/`pop` work at the back, `unshift`/`shift` at the front, and all change the array.
- `slice` copies a piece; `splice` cuts the array itself.
- `const b = a` shares; `[...a]` copies.
- Use spread, `concat`, `map`, `filter` and `flat` to make new arrays safely.

## Try this

In **Copying arrays**, change `const copy = [...cart]` to `const copy = cart`. Now both lines print `Pen, Bag`. Two names, one array.

## Check Yourself

## Common mistakes

| Mistake | Wrong idea | Correct idea | What goes wrong |
|---|---|---|---|
| `cart[cart.length]` for the last item | The last index is the length | It is `length - 1`, or use `at(-1)` | `undefined` |
| `const copy = cart` | That makes a copy | It shares the same array | Changing one changes both |
| `splice` when you meant `slice` | Both copy | `splice` changes the original | Items vanish from the list |
| `const n = cart.push(x)` then using `n` as the array | `push` returns the array | It returns the new length | `n.map is not a function` |
| `nested.flat()` on deep lists | It flattens everything | It removes one level | Inner arrays remain |

## Quick reference

<div className="tscroll">

| Syntax | Meaning |
|---|---|
| `[a, b, c]` | create an array |
| `Array.from({ length: n }, fn)` | create an array of `n` elements from a function |
| `array[i]`, `array.at(-1)` | read an element, or the last element |
| `array.length` | the number of elements |
| `push(x)` / `pop()` | add or remove at the end, changing the array |
| `unshift(x)` / `shift()` | add or remove at the start, changing the array |
| `slice(start, end)` | copy a section, without changing the array |
| `splice(start, count, ...items)` | remove and insert in place, changing the array |
| `[...array]` | a shallow copy |
| `array.map((x, i) => i === n ? value : x)` | a copy with one element replaced |
| `array.with(i, value)` | a copy with the element at `i` replaced |
| `[...array, x]`, `array.concat(x)` | a copy with an element added |
| `array.filter((x) => x !== value)` | a copy without matching elements |
| `[...array.slice(0, i), ...array.slice(i + 1)]` | a copy without the element at `i` |
| `[...first, ...second]`, `first.concat(second)` | a new array combining both |
| `array.flat(depth)` | unpack nested arrays |
| `array.flatMap(fn)` | map, then flatten one level |

</div>

## Exercises

## What to Remember

- An array is a numbered list, starting at 0.
- Know which methods change the array and which make a new one.
- Pages often redraw from an array after each change.

Next: **Array Operations**. Search, sort and summarise arrays with `find`, `sort` and `reduce`.
