Course outline · 0% complete

0/29 lessons0%

Course overview →

Creating and indexing arrays

lesson 4-1 · ~9 min · 10/29

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 .length property (no parentheses), not len(...).
  • Negative indexes do not work. fruits[-1] is undefined, not the last item. Use fruits[fruits.length - 1] or the modern method fruits.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.

"apple""banana""cherry"012fruits[i]indexes start at 0, the last index is length - 1
An array of three items. The pointer shows an index visiting each slot, from 0 up to length - 1.

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?