A variable was “a box with a name.” But when you want to hold Shima’s four favorite things, preparing four boxes and naming them like1, like2, and so on is a hassle. That’s where the array comes in. It’s a named shelf, with boxes lined up in a row.
How to make an array
const likes = ["drawing", "ramen", "games", "Shima"];| Part | Meaning |
|---|---|
[ ] | The “container” for the whole shelf |
, (comma) | The separator between values |
likes | The name given to the shelf |
Four values are now bundled under a single name, likes.
To take one out, use its number
To take one item off the shelf, add [number].
console.log(likes[0]);
console.log(likes[3]);The console shows “drawing” and “Shima.” …Wait, likes[3] is the fourth one?
Count how many are in it: length
Add .length and you learn how many values are on the shelf.
console.log(likes.length);The console shows 4. Whether the contents grow or shrink, likes.length always tells you the correct count.
You can add later: push
With push, you can add a value to the very back of the shelf.
likes.push("programming");
console.log(likes.length);The favorites have grown to five. Even for an array made with const, you can still add to or rearrange its contents (the rule is that swapping the whole shelf for a different one is what’s not allowed).
Swapping the contents
Specify a number and assign with =, and you can overwrite the value in that spot.
likes[1] = "udon";
console.log(likes[1]);The second item (index 1), “ramen,” changed to “udon.” Picture swapping only the item on the shelf’s second level. Whether you’re taking out or swapping in, you always specify the location as “name + number”—learn this shape and arrays are yours to command.
HTMLBullet points with listsThe way to make a “list for showing” (the HTML side) is in this lessonSummary of this lesson
- An array is
["value", "value", …]—a numbered shelf you put things in together - To take one out, use
name[number]. Numbers start at 0 .lengthtells you the count, and.push()lets you add