Every program you’ve written in JavaScript so far has kept one value in each variable, such as a name, a price, or a score. That works until the thing you care about is a list. Think of packing for a day hike, with a water bottle, a rain jacket, and a map today and five different things next weekend.
With one variable per item, your code would need a new variable every time the list grew, and a function couldn’t accept “however many items there are.” JavaScript solves this with an array, a single value that holds an ordered list of other values, so one variable can name the whole list.
In this course, you’ll go from reading and building small lists to writing functions that count, total, select, and find items in them, ending with an expedition supply checker that you build on-site.
This course assumes you can already run a script with node in the VS Code terminal, write functions with loops, if blocks, and return, and read a character from a string by its position. If you’ve arrived here directly and that sounds new, the earlier JavaScript Basics courses cover it.
In this lesson, you’ll type short examples into a script, predict what each prints, then run it to check your prediction.
Write Your First List
Open your course folder in VS Code, create packing.js in it, and type in a packing list for that day hike.
packing.js
const packingList = ["water bottle", "rain jacket", "map"];
console.log(packingList);
The square brackets and their contents form an array literal. You write the list’s items, often called elements, directly into your code, separated by commas. Each item here is a string with its own quotes.
Save the file and run it in the integrated terminal.
$ node packing.js
[ 'water bottle', 'rain jacket', 'map' ]
Node.js prints the whole array inside square brackets, with the items in the order you wrote them. The single quotes are only Node.js’s way of displaying strings inside a list, and your data hasn’t changed.
The order matters. An array remembers which item came first, second, and third, and a later lesson uses that to read items by position.
Count the Items With .length
How many things are in the list? Every array has a .length property that answers this. Change the second line of your script to print the length.
packing.js
const packingList = ["water bottle", "rain jacket", "map"];
console.log(packingList.length);
$ node packing.js
3
There are no parentheses after .length. It’s a property you read, not something you call.
You’ve already met .length on strings. Before you run the next snippet, recall what "water bottle".length gives and what it counts. Then compare it with the length of the whole list.
const packingList = ["water bottle", "rain jacket", "map"];
console.log(packingList.length);
console.log("water bottle".length);
3
12
The string has twelve characters, counting the space. For plain text like this, a string’s .length matches its character count, though a few characters, such as emojis, count as more. The array’s .length counts items instead, no matter how long each item is. Keep the whole list and its items apart in your head, because the coming lessons switch between them a lot.
Predict each length below. Then open the Node.js REPL by typing node in the terminal and enter the expressions one at a time:
[].length, for an array with nothing inside it["map"].length, for an array with one short item["salt, pepper", "matches"].length, for an array with a comma inside one string
Here’s what Node.js reports.
> [].length
0
> ["map"].length
1
> ["salt, pepper", "matches"].length
2
A pair of square brackets with nothing inside is an empty array, and its length is 0. It’s a perfectly good list, like an empty bag. The last answer is 2 because only the commas between items separate them. A comma inside the quotes is part of the string "salt, pepper". When you’re done, type .exit to leave the REPL.
Start Empty and Add Items With .push()
An array literal works when you know the whole list in advance. Often you don’t. You decide on the rain jacket after checking the weather, or a program adds an item only when a condition is true. Then you start with an empty array and add items as you go.
The .push() method appends an item, which means it adds the item to the end of the array. Replace your script with this version.
packing.js
const packingList = [];
packingList.push("water bottle");
packingList.push("rain jacket");
console.log(packingList);
console.log(packingList.length);
Before you run it, decide what the two lines of output will be. Then check.
$ node packing.js
[ 'water bottle', 'rain jacket' ]
2
Each call to .push() changed the array itself by adding one item at the end, so the items appear in the order you pushed them and the length grew from 0 by one each time.
Understand Why const Lets the List Grow
You declared packingList with const, and the array still changed. Didn’t const mean the value can’t change?
What const protects is the binding, the connection between the name packingList and the array it refers to. You can’t point that name at a different value later. Here’s what happens if you try.
const packingList = ["map"];
packingList = ["compass"];
TypeError: Assignment to constant variable.
The error message points out that you tried to assign a new value to a const name. Calling .push() doesn’t do that. It changes the contents of the array that packingList already names, so const has no objection. That’s why const is the usual choice for a list you build up.
For an optional check, start from const packingList = ["map"]; and decide which of these lines runs without an error and what each one would change:
packingList.push("compass");packingList = ["map", "compass"];
Line 1 runs. It changes the list, which now holds two items, and the binding stays the same. Line 2 raises the TypeError you just saw, because it tries to change the binding by pointing the name at a new array. For more practice telling the two apart, the mentor can quiz you with fresh snippets.
Read What .push() Gives Back
Like the functions you’ve written, .push() returns a value: the array’s new length as a number.
const packingList = ["water bottle", "rain jacket"];
const newLength = packingList.push("snacks");
console.log(newLength);
console.log(packingList);
3
[ 'water bottle', 'rain jacket', 'snacks' ]
So one call to .push() does two things. It changes the array, and it hands back a number telling you the new length. The list itself is still in packingList, and most of the time you’ll ignore the returned number.
Build a List Inside a Function
The on-site exercises in this course ask you to write functions that return a result for the tests to check. A function can start with an empty array, push items onto it, and return the finished list.
packing.js
function buildDayHikeList(extraItem) {
const items = [];
items.push("water bottle");
items.push("map");
items.push(extraItem);
return items;
}
console.log(buildDayHikeList("rain jacket"));
console.log(buildDayHikeList("sunscreen").length);
$ node packing.js
[ 'water bottle', 'map', 'rain jacket' ]
3
Each call runs the function’s body from the top and creates its own empty array. The rainy-day list gets a rain jacket, and the sunny-day list gets sunscreen, without either item leaking into the other list. The return line hands the whole array back to the caller, just as it would a number or a string.
Pack Your Own Bag
Now make the list your own. Pick a real outing, such as a beach day, a game night, or a long train ride. In packing.js, start with an empty array, push three or four items you’d actually bring, and print both the list and its length.
Before you run the script, write down the exact output you expect, including the order of the items and the length. Then run it and compare the two. If they differ, check the order of your .push() calls first.
Then make two changes and predict again before each run:
- Push one item that’s already on the list, such as a second
"snacks". - Push an empty string,
"", as if you’d forgotten to name an item.
Both times, the length goes up by one. An array keeps every item you push, including repeats and empty strings. Later lessons show how to count or skip particular items on purpose.
If your printed length matches the number of .push() calls on an empty array, your mental model is solid. For a second pair of eyes on your prediction, paste your script and the output you expected.
Get Ready for the Next Exercise
You can now read an array literal as an ordered list, predict its length, including 0 for an empty array, and build a list by pushing items onto it. Next up is Build a Packing List, an on-site coding exercise where you’ll write two functions: one that builds and returns a list, and one that counts its items.
On-site exercises run right in your browser. You write code in the editor on the page, then click Run Tests, and automated tests check what your function returns and report which checks passed. If a check fails or an error appears, read its message for a clue, edit your code, and click Run Tests again. Run early and often, even before your code is finished. If you want more room, switch the exercise to Full screen.