Arrays & Loops
- Arrays
- for loops
One variable, one value — fine for a single reading. But a whole strip of readings needs a different kind of wire.
Arrays: one label, many slots
let colors = ["red", "green", "blue"];An array is a power strip: one variable name, colors, but several
numbered sockets behind it. Each value inside the square brackets gets a
slot, counted from zero — colors[0] is "red", colors[1] is
"green", colors[2] is "blue". That zero start trips up everyone
once; after that, it's just how JavaScript counts.
Ask an array how many slots it's using with .length — colors.length
is 3 here, one more than the last valid index (2).
for: running the same step down every socket
Doing something once per item, by hand, doesn't scale past three colors. A for loop repeats a block automatically, once for every item:
for (let i = 0; i < colors.length; i++) {
console.log(colors[i]);
}(That's your browser's developer console talking — outside what this course's checks can see, but worth knowing it's there.)
Three parts inside the parentheses, separated by semicolons:
let i = 0— start: a counter, beginning at the first slot.i < colors.length— the condition: keep going while there's still a slot left to visit.i++— step: after each pass, move the counter forward by one slot (i++is shorthand fori = i + 1).
Each time through, colors[i] reaches into the slot the counter is
currently pointing at — first colors[0], then colors[1], then
colors[2], then the condition goes false and the loop stops.
Common mistake
Write i <= colors.length instead of i < colors.length, and the loop
reaches one slot past the end — colors[3] on a three-item array —
which doesn't error, it just quietly hands back undefined. .length
is a count, not a valid last index; the last real slot is always
.length - 1.
You can now repeat a decision across a whole list. Next lesson takes the biggest step of this unit: reaching out of your script and into the page itself.
The lab has a list to walk before you go.