Module 3: Conditions and Loops
Loops: for, while, and for...of
Choose the right loop for counting, repeated conditions, and iterable values.
Loops repeat work. A classic for loop is useful when the index or number of iterations matters:
for (let i = 1; i <= 5; i += 1) {
console.log(i);
}
A while loop repeats while its condition remains true. Make sure the loop body eventually changes the condition, or the loop may run forever.
let attempts = 0;
while (attempts < 3) {
console.log(`Attempt ${attempts + 1}`);
attempts += 1;
}
Iterating over values#
Use for...of for values from arrays, strings, and other iterables:
const languages = ["Java", "JavaScript", "Python"];
for (const language of languages) {
console.log(language);
}
Use for...in primarily when you deliberately need enumerable property keys of an object. For arrays, for...of or array methods are usually a better fit because for...in iterates keys and can include inherited enumerable properties.
Array methods#
Methods such as map, filter, and reduce are introduced in the arrays module. Use them when they express the transformation clearly. A normal loop is not wrong; choose the form that makes intent easiest to read.
Practice#
Loop through an array of prices and calculate the total. Then write a second loop that prints only prices greater than a chosen threshold.