JS · Lesson 4

Loops

Repeating code without writing it again

Imagine adding 100 stories to a page, one line of code each. Loops let you write the steps once and repeat them as many times as you need.

What you'll learn

  • How to repeat code a set number of times with for.
  • How to repeat while something is true with while and do...while.
  • How to go through every item of an array with for...of, and how to stop early with break.

Welcome to loops

A loop runs the same block of code again and again. Each time through is called a round, or an iteration. Every loop needs a way to stop, usually a condition like the ones in JS Lesson 3. When the condition becomes false, the loop ends and the code after it runs.

Loops and arrays go well together: one loop can visit every item of a list, no matter how long it is.

Think of P.E. class. "Run 5 laps" is a for loop: you know the count before you start. "Keep jogging while the whistle hasn't blown" is a while loop: you check before each lap. "Check each classmate's name on the list" is a for...of loop. And "stop once everyone is here" is break.

for is for a known number of rounds, while and do...while are for "until something changes", and for...of is for lists.

A closer look

The three parts of a for loop

lap++ is a short way to write lap = lap + 1. lap-- takes 1 away. The counter is often named i, short for index.

while and do...while

while checks its condition before each round, so if the condition is false at the start, the block never runs. do...while checks after each round, so its block always runs at least once.

for...of: one item at a time

for (const topic of topics) reads like a sentence: "for each topic of the topics list". Each round, topic holds the next item. You don't need a counter or topics[i], so there's less to get wrong.

Loops that never end

If the condition never becomes false, the loop runs forever and the page freezes. This is called an infinite loop. It usually happens when you forget to change the counter, like a while loop without readers = readers * 2. In WebCore, a loop that runs for too long is stopped for you, and the console says A loop ran for too long. In a normal browser, the tab would just stop responding.

Let's build it

Let's fill the Front Page Bytes topic list with loops. The HTML and CSS stay the same in every step: a heading and an empty list, <ul id="list">. Some steps add items to the list, and others write to the console.

Step 1: Repeat a set number of times with for

Your code
for (let lap = 1; lap <= 5; lap++) {  console.log("Lap " + lap);}console.log("Done running!");
What you see

Console

    Nothing here yet. console.log() writes here.

    lap starts at 1. Before each round, the loop checks lap <= 5, and after each round, lap++ adds 1. So the console shows Lap 1 to Lap 5. When lap becomes 6, the condition is false, the loop ends, and line 4 runs.

    Step 2: Build a list from an array

    Your code
    const topics = ["Phones", "Games", "Apps"];for (let i = 0; i < topics.length; i++) {  const item = document.createElement("li");  item.innerHTML = topics[i];  document.getElementById("list").appendChild(item);}
    What you see

    Console

      Nothing here yet. console.log() writes here.

      This time the counter i starts at 0, the first index, and stops before topics.length, which is 3. Each round uses topics[i] with the steps from JS Lesson 1: make an <li>, fill it, append it. Three lines inside the loop make three list items.

      Step 3: An easier way: for...of

      Your code
      const topics = ["Phones", "Games", "Apps"];for (const topic of topics) {  const item = document.createElement("li");  item.innerHTML = topic;  document.getElementById("list").appendChild(item);}
      What you see

      Console

        Nothing here yet. console.log() writes here.

        The page looks the same as in step 2, with less code. for...of gives you each item in turn as topic, so there's no counter and no [i].

        Step 4: Repeat while something is true

        Your code
        let readers = 1;while (readers < 100) {  readers = readers * 2;  console.log(readers);}console.log("Over 100 readers!");
        What you see

        Console

          Nothing here yet. console.log() writes here.

          The readers count doubles each round: 2, 4, 8, and so on. while checks readers < 100 before each round. After 128, the check is false, so the loop ends. Here, you didn't know the number of rounds before you started. That's when while is the right choice.

          Step 5: Run at least once with do...while

          Your code
          let tries = 10;do {  console.log("Try number " + tries);  tries++;} while (tries < 3);
          What you see

          Console

            Nothing here yet. console.log() writes here.

            tries is 10, so tries < 3 is false from the start. A while loop would never run. But do...while runs the block first and checks afterwards, so the console shows Try number 10 once.

            Step 6: Stop early with break

            Your code
            const topics = ["Phones", "Games", "Apps", "Robots"];for (const topic of topics) {  if (topic === "Apps") {    console.log("Found Apps!");    break;  }  console.log("Checking " + topic);}
            What you see

            Console

              Nothing here yet. console.log() writes here.

              The loop checks each topic. When it reaches "Apps", it logs Found Apps! and break stops the loop right there. "Robots" is never checked.

              Quick notes

              for A set number of times
              for (let i = 1; i <= 5; i++) { }

              How to use

              • for (start; condition; step) The three parts, with semicolons between them.
              • let i = 0 Start: makes the counter. Runs once, before the loop.
              • i < 5 Condition: checked before every round. The loop stops when it is false.
              • i++ Step: runs after every round. i++ adds 1 to i.

              Examples

              1. Count from 1 to 10.

                for (let i = 1; i <= 10; i++) {  console.log(i);}
              2. Count down from 5.

                for (let i = 5; i >= 1; i--) {  console.log(i);}
              3. Go through an array by index.

                for (let i = 0; i < names.length; i++) {  console.log(names[i]);}
              while While something is true
              while (readers < 100) { }

              How to use

              • while (condition) { } Repeats the block as long as the condition is true.
              • Something inside the block has to change, so the condition can become false.

              Examples

              1. Save money until you have 500.

                let savings = 0;while (savings < 500) {  savings = savings + 100;}
              2. Halve a number until it is small.

                let n = 64;while (n > 1) {  n = n / 2;}
              do...while At least once
              do { } while (tries < 3);

              How to use

              • do { } while (condition); Runs the block first, then checks the condition.
              • The block always runs at least once, even if the condition is false.

              Examples

              1. Ask once, then ask again only if needed.

                let tries = 0;do {  tries++;} while (tries < 3);
              for...of Each item of a list
              for (const topic of topics) { }

              How to use

              • for (const item of list) { } Goes through a list, one item at a time.
              • item Holds the current item. Pick any name you like.
              • No counter needed. It stops after the last item.

              Examples

              1. Greet each student.

                for (const name of ["Ana", "Ben"]) {  console.log("Hi " + name);}
              2. Add up a list of prices.

                let total = 0;for (const price of [25, 40, 15]) {  total = total + price;}
              break Stop the loop now
              break;

              How to use

              • break; Stops the loop right away.
              • The code after the loop keeps running. break also ends a case in a switch.

              Examples

              1. Stop at the first negative number.

                for (const n of numbers) {  if (n < 0) {    break;  }  console.log(n);}

              Common mistakes

              These are mistakes many beginners make. Each mini browser shows what really happens.

              Going one step too far

              The mistake
              const topics = ["Phones", "Games", "Apps"];for (let i = 0; i <= topics.length; i++) {  const item = document.createElement("li");  item.innerHTML = topics[i];  document.getElementById("list").appendChild(item);}
              What you see

              Console

                Nothing here yet. console.log() writes here.

                i <= topics.length lets i reach 3. There's no topics[3], so the fourth list item says undefined.

                Tip: Loop with i < list.length, not i <= list.length. The last index is length - 1.

                A semicolon right after for ( )

                The mistake
                for (let lap = 1; lap <= 3; lap++); {  console.log("Lap " + lap);}
                What you see

                Console

                  Nothing here yet. console.log() writes here.

                  The ; after for ( ) ends the loop right there, so the loop repeats nothing. The { } below is no longer part of it. It runs once on its own, where lap doesn't exist, so the console shows lap is not defined.

                  Tip: Start the block { right after the closing parenthesis of for ( ), with no semicolon between them.

                  Making the element outside the loop

                  The mistake
                  const topics = ["Phones", "Games", "Apps"];const item = document.createElement("li");for (const topic of topics) {  item.innerHTML = topic;  document.getElementById("list").appendChild(item);}
                  What you see

                  Console

                    Nothing here yet. console.log() writes here.

                    There's only one <li>, made before the loop. Each round changes its text and appends the same element again, which only moves it. So the list shows just one item: the last one, Apps.

                    Tip: Make a new element inside the loop, so every round gets its own.

                    Test your knowledge

                    Write JavaScript in the JS tab. The fruits array is ready for you. If a loop runs forever by mistake, WebCore stops it after a moment and says so in the console.

                    No clicking needed. Each goal gets a check mark by itself once your code does it.

                    1. Use a for loop with a counter, like one that logs 1 to 5. not done yet
                    2. Use for...of to go through the fruits array. not done yet
                    3. Add every fruit to #list as its own <li>. not done yet
                    4. Use a while or a do...while loop. not done yet
                    5. Stop a loop early with break. not done yet
                    Your code
                    What you see

                    Console

                      Nothing here yet. console.log() writes here.

                      Try an exercise

                      Recap

                      • for (start; condition; step) repeats a set number of times. i++ adds 1 to the counter after each round.
                      • while repeats as long as its condition is true, checking first. do...while checks afterwards, so it always runs once.
                      • for...of goes through every item of an array, and break stops a loop early. Make sure every loop can end.

                      References

                      Lesson content prepared by the WebCore F.E. team for beginner learners. The following references were used in preparing this lesson.

                      • ECMA International. ECMAScript Language Specification (official specification). Open reference