Quiz
Warm-up from lesson 3-3: which loop visits each item of a collection directly, with no counter?
Arrays are JavaScript's lists
Real data comes in bunches: search results, chat messages, rows of a spreadsheet. An array lets one variable hold the whole bunch in order, which is what gives the loops from unit 3 something worth looping over.
What Python calls a list, JavaScript calls an array. Same square brackets, same zero-based indexing:
const fruits = ["apple", "banana", "cherry"]; console.log(fruits[0]); // "apple" console.log(fruits.length); // 3
Two differences from Python to absorb:
- Length is the
.lengthproperty (no parentheses), notlen(...). - Negative indexes do not work.
fruits[-1]isundefined, not the last item. Usefruits[fruits.length - 1]or the modern methodfruits.at(-1).
And one JavaScript quirk: reading an index that does not exist gives undefined instead of raising an error like Python's IndexError. Your program keeps running, often with confusing results later, so watch your bounds.
Code exercise · javascript
Run it. Note the two ways to reach the last item, and what happens with a negative index.
Code exercise · javascript
Your turn. Create a const array named colors holding red, green, blue (as strings). Print three lines: the first color, the last color using .at(-1), and the array length.
Quiz
const nums = [10, 20, 30]; What does nums[3] give you?