Himanshu SharmaSoftware engineer
Let’s talk

JavaScript · Lesson 28 of 58

Arrays

Store ordered lists of values in JavaScript arrays, read and change items by index, use length, loop over items and understand copies versus references.

14 minArrays and objectsUpdated 14 November 2026

Awaiting technical review. This lesson is readable but not yet listed in search engines.

By the end of this lessonCreate arrays, read and change items by index, loop over them with for...of, and explain why copying an array needs more than an equals sign.

After this lesson you can keep a list of things in one variable, pick out any item, change it, walk through the whole list, and avoid the classic trap of accidentally changing an array you thought you had copied.

What an array is

So far each variable has held one value. Real programs deal with lists: the names of students, the prices in a basket, the lines of a file. An array holds many values in order, written inside square brackets and separated by commas.

javascript
const fruits = ["apple", "banana", "cherry"];
const mixed = [42, "hello", true, null];   // any types, even mixed
const empty = [];

Arrays can hold anything, including other arrays and objects. In practice you will usually keep one kind of thing in each array, because that makes the code that processes it simpler.

Indexes start at zero

Each item has a position called an index. Counting starts at 0, not 1. You read an item with square brackets after the array name.

javascript
const fruits = ["apple", "banana", "cherry"];
console.log(fruits[0]);       // apple
console.log(fruits[2]);       // cherry
console.log(fruits[3]);       // undefined, there is no fourth item
console.log(fruits.length);   // 3

The length property is the number of items, so the last index is always length - 1. Modern JavaScript also has at(), which accepts negative numbers to count from the end: fruits.at(-1) is "cherry", and fruits.at(-2) is "banana". Reading an index that does not exist is not an error; you simply get undefined.

Changing an array

Assign to an index to replace an item. Assigning to the next free index adds one.

html
<pre id="out"></pre>
<script>
  const out = document.getElementById("out");
  const log = (...parts) => { out.textContent += parts.join(" ") + "\n"; };

  const fruits = ["apple", "banana", "cherry"];
  fruits[1] = "blueberry";   // replace
  fruits[3] = "date";        // add at the end
  log(fruits.join(", "));
  log("length:", fruits.length);
  fruits.length = 2;         // shrinking length cuts items off
  log(fruits.join(", "));
</script>

Notice that you can change items of an array declared with const. The const keyword stops you from pointing the name at a different array; it does not freeze the contents. This surprises many beginners, and it comes back in the lesson on objects.

Writing to a far-away index such as fruits[10] = "x" leaves empty gaps in between. Avoid it. Add items with push, covered in adding, removing and searching arrays.

Looping over an array

The cleanest way to visit every value is for...of:

javascript
const scores = [8, 5, 9];
let total = 0;
for (const score of scores) {
  total += score;
}
console.log(total);   // 22

You can still use a classic for loop with an index when you need the position:

javascript
const names = ["Asha", "Ben", "Chen"];
for (let i = 0; i < names.length; i++) {
  console.log(i, names[i]);
}
// 0 Asha
// 1 Ben
// 2 Chen

There is also names.forEach((name, i) => { ... }), which calls a function for each item. A limitation worth knowing: you cannot break out of forEach, while you can inside for...of. Do not use for...in on arrays; it loops over keys as strings and can include unexpected properties.

Arrays are references

This is the most important idea in the lesson. An array is an object, and a variable holding it really holds a reference to it, like an address. Copying the variable copies the address, not the list.

html
<pre id="out"></pre>
<script>
  const out = document.getElementById("out");
  const log = (...parts) => { out.textContent += parts.join(" ") + "\n"; };

  const original = [1, 2, 3];
  const alias = original;        // same array, two names
  const copy = [...original];    // a new array with the same items

  alias.push(4);
  log("original:", original.join(","));
  log("alias:   ", alias.join(","));
  log("copy:    ", copy.join(","));
  log("original === alias?", original === alias);
  log("original === copy?", original === copy);
</script>

The output shows original and alias both containing 1,2,3,4, while copy is untouched. Comparing two arrays with === also compares references, so two separate arrays with identical contents are not equal.

[...original] and original.slice() make a shallow copy: the new array is separate, but if its items are themselves arrays or objects, those inner items are still shared. For a full independent duplicate use structuredClone(original), available in all current browsers and in Node 17 and later.

Arrays of arrays

An item can be another array, which gives you a grid:

javascript
const grid = [
  [1, 2, 3],
  [4, 5, 6],
];
console.log(grid[1][2]);   // 6, row 1, column 2

Read the double index from left to right: first pick the row, then the item within it.

Useful checks

  • Array.isArray(x) tells you whether x is an array. typeof [] says "object", which is not helpful.
  • arr.includes("apple") tells you whether a value is present.
  • arr.join(", ") turns an array into a string.

Common mistakes

  • Expecting the first item at index 1. The first item is arr[0].
  • Using arr[arr.length] for the last item. That index is one past the end. Use arr[arr.length - 1] or arr.at(-1).
  • Thinking const b = a makes a copy. It makes a second name for the same array, so changes through one name show up through the other.
  • Comparing arrays with === and expecting equal contents to match.
  • Printing an array inside a string and being surprised: "List: " + [1, 2] gives List: 1,2. Use join to control the format.

Exercise

Create an array of five numbers. Write a loop that finds the largest number without using Math.max. Then make a copy of the array, change the first item in the copy, and show that the original did not change.

Show one possible answer
html
<pre id="out"></pre>
<script>
  const out = document.getElementById("out");
  const log = (...parts) => { out.textContent += parts.join(" ") + "\n"; };

  const numbers = [4, 19, 7, 12, 3];
  let largest = numbers[0];
  for (const n of numbers) {
    if (n > largest) largest = n;
  }
  log("largest:", largest);

  const copy = [...numbers];
  copy[0] = 100;
  log("original:", numbers.join(","));
  log("copy:", copy.join(","));
</script>

Next: adding, removing and searching arrays.

Key points

  • An array is an ordered list. Items are read by index, and the first index is 0.
  • length tells you how many items there are, and the last item is at index length - 1 (or use at(-1)).
  • Assigning to a new index or changing an item mutates the array in place.
  • for...of loops over the values; forEach calls a function for each one.
  • Arrays are objects, so copying with = copies the reference, not the list. Use [...arr] for a shallow copy.

Check yourself

1. Given const a = ['x', 'y', 'z'], what is a[1]?
2. What does a.at(-1) return for a three-item array?
3. After const b = a; b.push(4), what happens to a?
4. Which line makes a shallow copy of an array?