Line At A Time
Lesson 19: Adding It Up
Adding It Up Total up all the numbers in an array.
1const prices = [2, 4, 6];
2let total = 0;
3for (const price of prices) {
4 total = total + price;
5}
6console.log(total);
Terminal
$ node main.js
12
Every line, explained
const prices = [2, 4, 6];
An array stores several values in one variable. The values go between square brackets, separated by commas. This one holds numbers; arrays can hold any kind of value.
let total = 0;
let creates a variable whose value you PLAN to change later. The modern rule of thumb: use const unless you know the value will change; then use let. (You may see var in old code; it went out of style years ago.) total starts at 0 and will collect the running sum. It changes, so it must be let.
for (const price of prices) {
for...of visits each item in the array, one trip around the loop per item. Each time, the loop variable holds the current item, and since we never reassign it ourselves, it is declared with const. This is the modern JavaScript way to loop over an array.
total = total + price;
Each trip adds the current price onto total: 0+2=2, 2+4=6, 6+6=12. (JavaScript has a shortcut for this too: total += price.)
}
This } closes the for loop.
console.log(total);
console.log(...) prints whatever is inside the round brackets to the terminal, then moves to a new line. console is the terminal itself, log is the tool that writes to it, joined with a dot. After the loop finishes, total is 12.