Arrays & ObjectsCore· 40 min read

Arrays

Store lists of data — the workhorse structure behind almost every app.

What you will learn

  • Create and read arrays
  • Add and remove items
  • Use length and indexes

A list of values

An array holds many values in order, inside [ ]. Each item has an index — and indexes start at 0.

Indexes start at 0
<script>
  const colors = ["red", "green", "blue"];
  document.write(colors[0] + "<br>");   // red  (first)
  document.write(colors[2] + "<br>");   // blue (third)
  document.write("Total: " + colors.length);
</script>
Live preview

We read items by their index in square brackets. colors[0] is the first item ("red") because counting starts at 0, and colors[2] is the third ("blue"). colors.length counts how many items there are — 3.

Note: Output: red blue Total: 3

Watch out: The first item is index 0, not 1. So the last item is at array.length - 1. This zero-based counting is the #1 beginner gotcha.

Add and remove

MethodDoes
.push("x")Add to the end
.pop()Remove from the end
.unshift("x")Add to the start
.shift()Remove from the start
.lengthHow many items
push, unshift, join
<script>
  const tasks = ["Wake up", "Code"];
  tasks.push("Sleep");        // add to end
  tasks.unshift("Coffee");    // add to start
  document.write(tasks.join(" → "));
</script>
Live preview

We start with two tasks. push("Sleep") adds "Sleep" to the end, and unshift("Coffee") adds "Coffee" to the start. So the list becomes Coffee, Wake up, Code, Sleep. join(" → ") then glues every item into one string with " → " between each.

Note: Output: Coffee → Wake up → Code → Sleep

Q. What is the index of the FIRST item in an array?

Answer: Arrays are zero-indexed: the first item is at index 0, so the last is at length - 1.

✍️ Practice

  1. Make an array of five subjects and print the first and last using indexes.
  2. Start with an empty array and push three items into it.

🏠 Homework

  1. Build a “playlist” array, add and remove songs, and print the final list.
Want to learn this with a mentor?

CodingClave runs guided, project-based training (28-day, 45-day & 6-month batches).

Explore Training →