Course curriculum
Arrays and loops
Store collections, iterate with for...of and accumulate results without duplicating statements.
About 10 minutes · BeginnerRead an ordered collection
An array stores values in order. Indexes start at zero, so scores[0] reads the first score. length gives the number of elements.
for...of visits values directly. Use it when you need each value rather than its property name; for...in serves a different purpose.
const scores = [60, 75, 81];
let total = 0;
for (const score of scores) {
total += score;
}
console.log(total);216
Repeat a fixed number of times
A traditional for loop has initialization, a condition and an update. The condition is checked before every iteration.
Use index < array.length, not <=, to avoid reading one element past the end. Accessing that missing element returns undefined.
const topics = ["Values", "Conditions", "Loops"];
for (let i = 0; i < topics.length; i += 1) {
console.log(`${i + 1}. ${topics[i]}`);
}1. Values 2. Conditions 3. Loops
Select a subset
filter creates a new array containing values for which the callback returns a truthy result. It does not remove values from the original array.
The arrow function below receives one score and returns the comparison result. We will build named reusable functions next.
const scores = [35, 62, 40, 28];
const passed = scores.filter(score => score >= 40);
console.log(passed.join(", "));62, 40
Try it yourself
Count how many values in [2, 7, 4, 9] are even. A value is even when value % 2 === 0.
Show a possible solution
const values = [2, 7, 4, 9];
console.log(values.filter(value => value % 2 === 0).length); // 2Keep exploring: official JavaScript documentation.