← React / TypeScript

React / TypeScript · 04 / 18

Loops in JavaScript

Iterate over values and calculate a total.

  • Small
  • Basics
  • 15 min

Prerequisites: Operators, comparisons and if

An array stores several values in order. A loop applies a rule to each value. Our three cost amounts are in an array. for...of provides the values directly. A traditional for loop helps when you need the index.

Example files

01Iterate over values

total starts at 0. Each iteration adds one amount in cents. += is shorthand for total = total + cost. After the loop, total contains the sum.

loops.mjs · javascriptOpen file
const costs = [12990, 1990, 20];
let total = 0;
for (const cost of costs) {
  total += cost;
}
console.log(total);

Run / check

node loops.mjs

02Understand indexes

Array indexes start at 0. i < costs.length prevents accessing a nonexistent item. If you do not need the index, for...of is usually clearer.

03Check meaning

Cost amounts can be added when they have the same currency and meaning. Mileage readings are cumulative values instead. A loop cannot make a domain-invalid calculation correct.

Expected result

Total cost: 15000 cents

Your exercise

Also count how many entries contain at least 1000 cents.

Show the solution and explanation

Declare let count = 0 before the loop. Increase count inside if (cost >= 1000). The result is 2. total and count answer different questions about the same data.

Project context and sources

The example is simplified for learning. The linked source version shows its use in the project and the checks applied there.