Skip to content

For Loops

You have an array. Now you want to go through each item and do something with it.

In Python you write:

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

JavaScript has a loop that does exactly the same thing — for...of:

let fruits = ["apple", "banana", "cherry"]

for (let fruit of fruits) {
  console.log(fruit)
}

Same logic. The condition goes in parentheses. The body goes in curly braces. for...of is the cleanest way to loop through an array in JavaScript and the closest thing to Python's for ... in ....


The classic for loop

You will also see this version — especially in older code and tutorials:

let fruits = ["apple", "banana", "cherry"]

for (let i = 0; i < fruits.length; i++) {
  console.log(fruits[i])
}

Breaking it down:

  • let i = 0 — start counting from zero
  • i < fruits.length — keep going while i is less than the number of items
  • i++ — add 1 to i after each loop (same as i = i + 1 in Python)

Use for...of when you just need each item. Use the classic for loop when you also need the position number.


Looping through an array of objects

let patients = [
  { name: "Alice", age: 24 },
  { name: "Bob",   age: 31 },
  { name: "Carol", age: 19 }
]

for (let patient of patients) {
  console.log(patient.name + " is " + patient.age + " years old")
}

Output:

Alice is 24 years old
Bob is 31 years old
Carol is 19 years old

Same pattern as Jinja2's {% for patient in patients %} — just running in JavaScript instead of a template.


Building output on the page

You can use a loop to build up a string of HTML and put it all on the page at once:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Patients</title>
  </head>
  <body>

    <div id="output"></div>

    <script>
      let patients = [
        { name: "Alice", age: 24 },
        { name: "Bob",   age: 31 },
        { name: "Carol", age: 19 }
      ]

      // build up a string of HTML tags
      let html = ""
      for (let patient of patients) {
        html = html + "<p>" + patient.name + " — " + patient.age + "</p>"
      }

      // put the whole thing onto the page at once
      let outputBox = document.getElementById("output")
      outputBox.innerHTML = html
    </script>

  </body>
</html>

.innerHTML is like .innerText but it understands HTML tags. You built a string of <p> tags in the loop and handed the whole thing to the page at once.


Challenge

Take the patients array above. Use .push() to add two more patients. Then loop through all of them and display each name and age inside <li> tags — wrap the whole thing in a <ul> by adding "<ul>" before the loop and "</ul>" after, then set outputBox.innerHTML.


← Arrays    Next: Do This After →