Add up an array with a counting for loop, count down with while, and stop a for…of loop early with break.
JavaScript · beginner · 7 min · 24 steps · free
const prices = [4, 10, 7];
let total = 0;
for (let i = 0; i < prices.length; i++) {
total += prices[i];
}
let countdown = 3;
while (countdown > 0) {
console.log(countdown);
countdown--;
}
for (const price of prices) {
if (price > 8) break;
console.log('cheap:', price);
}prices is created and points to a new Array: [4, 10, 7].total is created with the value 0.total += prices[i] adds the price at index 0: total = 4.i < prices.length is true, so the loop body runs.total changes from 4 to 14.i < prices.length is true, so the loop body runs.total changes from 14 to 21.countdown is created with the value 3. i goes out of scope and disappears.3.countdown changes from 3 to 2.countdown > 0 is true, so the loop body runs.2.countdown changes from 2 to 1.countdown > 0 is true, so the loop body runs.1.countdown changes from 1 to 0.countdown > 0 is false, so the loop ends.price > 8 is false, so the if-block is skipped.cheap: 4.break ends the loop at once. 7 is never looked at.Answer: 2
Answer: Skips to the next pass
← if, else and the Ternary · Functions and the Call Stack →