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.
<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>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
| Method | Does |
|---|---|
.push("x") | Add to the end |
.pop() | Remove from the end |
.unshift("x") | Add to the start |
.shift() | Remove from the start |
.length | How many items |
<script>
const tasks = ["Wake up", "Code"];
tasks.push("Sleep"); // add to end
tasks.unshift("Coffee"); // add to start
document.write(tasks.join(" → "));
</script>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?
✍️ Practice
- Make an array of five subjects and print the first and last using indexes.
- Start with an empty array and
pushthree items into it.
🏠 Homework
- Build a “playlist” array, add and remove songs, and print the final list.