Loops

Computer Science · JavaScript

Question 1 of 10

0

    What does this JavaScript code log? let sum = 0; for (let i = 4; i <= 7; i += 1) { sum += i; } console.log(sum);

    Decimals (0.75 or 0,75), fractions (3/4) and mixed numbers (1 1/2) are accepted. Do not use thousands separators.

    How to type your answer
    • Fractions: 3/4. Mixed numbers: 1 1/2.
    • Decimals with a point or a comma: 0.75 or 0,75.
    • Negative numbers start with a minus: -3/4.
    • Percentages need the % sign: 75%.

    Stuck? Read the explanation

    Unlocks at a streak of 5 correct answers in a row.

    Print a free worksheet (PDF)

    Embed this practice on your site or class page

    Paste this HTML into your page. Students practise right there; it is free and needs no account.

    Loops explained

    A loop repeats a block of code while a condition holds, or once for each item in a collection. JavaScript offers for, while, do...while, for...of and for...in loops.

    A classic for loop has three parts in its header: an initialisation, a condition checked before each pass, and an update run after each pass. A while loop checks its condition before each pass, so it may run zero times. A do...while loop checks after each pass, so its body always runs at least once.

    let total = 0;
    for (let i = 1; i <= 5; i++) {
        if (i === 3) continue;
        total += i;
    }
    console.log(total);
    

    for...of visits each value of an array or string. for...in visits the keys of an object, and it is better avoided for arrays. break leaves the loop at once, and continue skips the rest of the current pass.

    Caveat: a loop whose condition never becomes false runs forever and freezes the page, so check that the variable changes towards the exit condition.

    Worked example

    The values of i are 1 to 5. At i = 1 total becomes 1, and at i = 2 it becomes 3. At i = 3 the continue skips the addition. At i = 4 total becomes 7, and at i = 5 it becomes 12. The output is 12, which equals 1 + 2 + 4 + 5.

    What you will practise

    New numbers every time you practise. Levels: Easy, Medium, Hard. Each answer is followed by a worked explanation.

    Example questions

    • Easy

      What does this JavaScript code log?

      let sum = 0; for (let i = 0; i <= 11; i += 1) { sum += i; } console.log(sum);

    • Medium

      What does this JavaScript code log?

      let i = 0; let total = 0; while (i < 7) { i += 1; if (i % 5 === 0) { continue; } total += i; } console.log(total);

    • Hard

      What does this JavaScript code log?

      let count = 0; let i = 6; do { count += 1; i += 1; } while (i < 5); outer: for (let a = 0; a < 3; a++) { for (let b = 0; b < 5; b++) { if (a * b === 6) { break outer; } count += 1; } } console.log(count);