> ## Documentation Index
> Fetch the complete documentation index at: https://js.maxbraglia.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Loops

> Repeat actions and iterate over data with JavaScript loops

## Looping in JavaScript

Loops let you repeat actions and iterate over data. JavaScript has several loop types, but you'll use two of them most of the time: `for...of` and the classic `for` loop.

## for...of — iterate over arrays

The cleanest way to loop through an array:

```javascript theme={null}
const fruits = ["Apple", "Banana", "Cherry"];

for (const fruit of fruits) {
  console.log(fruit);
}
// Apple
// Banana
// Cherry
```

<Tabs>
  <Tab title="JavaScript">
    ```javascript theme={null}
    for (const item of items) {
      console.log(item);
    }
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    for item in items:
        print(item)
    ```
  </Tab>
</Tabs>

JavaScript's `for...of` is Python's `for...in`. Same concept, different keyword. Use `const` for the loop variable if you don't need to reassign it inside the loop.

### When you need the index

```javascript theme={null}
const users = ["Sarah", "John", "Alice"];

// Use .forEach() with index
users.forEach((user, index) => {
  console.log(`${index + 1}. ${user}`);
});
// 1. Sarah
// 2. John
// 3. Alice

// Or use .entries()
for (const [index, user] of users.entries()) {
  console.log(`${index + 1}. ${user}`);
}
```

<Tabs>
  <Tab title="JavaScript">
    ```javascript theme={null}
    for (const [index, user] of users.entries()) {
      console.log(`${index}: ${user}`);
    }
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    for index, user in enumerate(users):
        print(f"{index}: {user}")
    ```
  </Tab>
</Tabs>

`.entries()` is JavaScript's equivalent of Python's `enumerate()`.

## for...in — iterate over object keys

```javascript theme={null}
const user = { name: "Sarah", age: 28, role: "admin" };

for (const key in user) {
  console.log(`${key}: ${user[key]}`);
}
// name: Sarah
// age: 28
// role: admin
```

<Warning>
  `for...in` is for **objects**. `for...of` is for **arrays**. Mixing them up is a common mistake. `for...in` on an array gives you index strings ("0", "1", "2"), not the values.
</Warning>

For objects, you can also use `Object.entries()` which is often cleaner:

```javascript theme={null}
const user = { name: "Sarah", age: 28, role: "admin" };

for (const [key, value] of Object.entries(user)) {
  console.log(`${key}: ${value}`);
}
```

## Classic for loop

The traditional loop with a counter variable. Use it when you need precise control over the iteration:

```javascript theme={null}
for (let i = 0; i < 5; i++) {
  console.log(i);
}
// 0, 1, 2, 3, 4
```

Three parts: `for (initialization; condition; update)`

* **initialization**: `let i = 0` — runs once before the loop
* **condition**: `i < 5` — checked before each iteration
* **update**: `i++` — runs after each iteration

### Practical example

```javascript theme={null}
// Generate a grid of items
const rows = 3;
const cols = 4;

for (let row = 0; row < rows; row++) {
  for (let col = 0; col < cols; col++) {
    console.log(`Cell [${row}, ${col}]`);
  }
}
```

### Looping backwards

```javascript theme={null}
const items = ["first", "second", "third"];

for (let i = items.length - 1; i >= 0; i--) {
  console.log(items[i]);
}
// third, second, first
```

## while and do...while

For loops where you don't know the count in advance:

```javascript theme={null}
// while — checks condition first
let attempts = 0;
while (attempts < 3) {
  console.log(`Attempt ${attempts + 1}`);
  attempts++;
}

// do...while — runs at least once, checks condition after
let input;
do {
  input = getInput(); // Runs at least once
} while (!isValid(input));
```

<Info>
  `while` loops are uncommon in web development. You'll mostly use `for...of` for arrays and array methods like `.map()` and `.forEach()`. But `while` is useful for retry logic and polling patterns.
</Info>

## break and continue

Control the flow inside loops:

```javascript theme={null}
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

// break — exit the loop entirely
for (const num of numbers) {
  if (num > 5) break;
  console.log(num);
}
// 1, 2, 3, 4, 5

// continue — skip to the next iteration
for (const num of numbers) {
  if (num % 2 === 0) continue; // Skip even numbers
  console.log(num);
}
// 1, 3, 5, 7, 9
```

## Loops vs array methods

In modern JavaScript, you'll often choose between a loop and an array method. Here's when to use each:

| Task                           | Use                                          |
| ------------------------------ | -------------------------------------------- |
| Transform each item            | `.map()`                                     |
| Keep some items                | `.filter()`                                  |
| Find one item                  | `.find()`                                    |
| Check if something exists      | `.includes()` or `.some()`                   |
| Calculate a total              | `.reduce()`                                  |
| Side effects (log, DOM update) | `.forEach()` or `for...of`                   |
| Need `break`/`continue`        | `for...of` or `for`                          |
| Need the index                 | `.forEach()` or `for...of` with `.entries()` |

```javascript theme={null}
// Array method approach — usually preferred
const activeUsers = users.filter(u => u.active).map(u => u.name);

// Loop approach — needed for complex logic or early exit
const results = [];
for (const user of users) {
  if (user.role === "banned") continue;
  if (results.length >= 10) break;
  if (user.active) {
    results.push(user.name);
  }
}
```

<Tip>
  Prefer array methods when possible — they're more readable and less error-prone. Use `for...of` when you need `break`, `continue`, or complex multi-step logic inside the loop.
</Tip>

## What's next?

You've covered working with data — arrays, objects, destructuring, spread, JSON, conditionals, and loops. This is the toolbox you'll use in every web application.

Next up: asynchronous JavaScript. This is where things get interesting — you'll learn how JavaScript handles operations that take time, like fetching data from your FastAPI backend.

<Card title="Why async matters" icon="bolt" href="/async-apis/why-async-matters">
  Understand why JavaScript handles time differently
</Card>
