Javascript in 100 bits

Course by zooboole,

Last Updated on 2025-01-28 08:04:00

Lesson 8 - Loops in JavaScript (For Loop)

Loops are used to walk through a list of things or ideas. When you are asked to count students in a class for eample, you need to walk pass each student or walk your finder pointing to each student. Loops are used in the programming world as well to walk through many things, like shopping list, a list of to-dos.

The interesting part is that, whenever we reach every element, we can apply individual action to each, independently from what happens with other.

In Javascript, we have a few constructs we can use to perform looping such as for loop, array.each,while, do-while.

Today''s snipet will focus only on the for loop.

for (let i = 0; i < 5; i++) {
  console.log("This is iteration number: " + i);
}

Explanation:

A for loop allows you to repeat a block of code a specific number of times. The loop consists of three parts:

  • Initialization (let i = 0): Set the starting point.
  • Condition (i < 5): The loop will continue as long as this condition istrue.
  • Increment (i++): After each iteration, i increases by 1.

Try your hand:

1. Create a File:

Create a new file named lesson8-for-loop.html.

2. Write the Code:

Copy and paste the following code into your file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Lesson 8 - For Loop</title>
</head>
<body>
    <script>
        for (let i = 0; i < 5; i++) {
            console.log("This is iteration number: " + i);
        }
    </script>
</body>
</html>

Save the file in your folder.

3. Preview the File:

  • Open the file in your browser and access the developer console.
  • Observe the output:
This is iteration number: 0
This is iteration number: 1
This is iteration number: 2
This is iteration number: 3
This is iteration number: 4

4. Experiment:

  • Change the condition from i < 5 to i < 10 and refresh the browser to see more iterations.
  • You can also try adjusting the increment value (i++ to i += 2 for example) to change the loop behavior