# Loops

Course: [JavaScript](https://www.devtutorials.ai/learn/javascript) · Section: Basics
Source: https://www.devtutorials.ai/learn/javascript/basics/loops

> Repeating work with for, while and do...while, walking objects with for...in and arrays with for...of, and controlling a loop with break and continue.

## What Is a Loop?

**Loop** = code that repeats while a condition stays true.

- Print 5 ticket numbers without writing 5 lines.
- Add up every price in a cart.
- Stop as soon as you find what you want.

**Simple lesson:** write the work once, and the loop repeats it for each item.

### A Real-World Example

A cart has 3 items: ₹120, ₹80 and ₹45.
A loop visits each price and adds it to a total.
With 300 items, the same 3 lines of code still work.

<figure className="ts-fig">
  <svg viewBox="0 0 560 170" role="img" aria-label="A pointer moves across three cart prices, 120, 80 and 45, while a running total grows from 0 to 245." width="100%">
    <rect x="0" y="0" width="560" height="170" rx="12" fill="#f8fafc" stroke="#e2e8f0" />
    <rect x="40" y="40" width="90" height="44" rx="8" fill="#eff6ff" stroke="#2563eb" />
    <text x="85" y="68" textAnchor="middle" fontSize="15" fontFamily="monospace" fill="#1e40af">₹120</text>
    <rect x="150" y="40" width="90" height="44" rx="8" fill="#eff6ff" stroke="#2563eb" />
    <text x="195" y="68" textAnchor="middle" fontSize="15" fontFamily="monospace" fill="#1e40af">₹80</text>
    <rect x="260" y="40" width="90" height="44" rx="8" fill="#eff6ff" stroke="#2563eb" />
    <text x="305" y="68" textAnchor="middle" fontSize="15" fontFamily="monospace" fill="#1e40af">₹45</text>
    <polygon points="0,0 -8,-14 8,-14" fill="#ca8a04">
      <animateTransform attributeName="transform" type="translate" values="85,36;195,36;305,36;85,36" keyTimes="0;0.33;0.66;1" calcMode="discrete" dur="3s" repeatCount="indefinite" />
    </polygon>
    <rect x="400" y="40" width="130" height="44" rx="8" fill="#f0fdf4" stroke="#16a34a" />
    <text x="465" y="68" textAnchor="middle" fontSize="15" fontFamily="monospace" fill="#166534">total</text>
    <text x="465" y="115" textAnchor="middle" fontSize="15" fontFamily="monospace" fill="#166534">₹120<animate attributeName="opacity" values="1;0;0;0" keyTimes="0;0.33;0.66;1" calcMode="discrete" dur="3s" repeatCount="indefinite" /></text>
    <text x="465" y="115" textAnchor="middle" fontSize="15" fontFamily="monospace" fill="#166534">₹200<animate attributeName="opacity" values="0;1;0;0" keyTimes="0;0.33;0.66;1" calcMode="discrete" dur="3s" repeatCount="indefinite" /></text>
    <text x="465" y="115" textAnchor="middle" fontSize="15" fontFamily="monospace" fill="#166534">₹245<animate attributeName="opacity" values="0;0;1;0" keyTimes="0;0.33;0.66;1" calcMode="discrete" dur="3s" repeatCount="indefinite" /></text>
    <text x="280" y="150" textAnchor="middle" fontSize="12" fill="#475569">One pass of the loop for each price.</text>
  </svg>
  <figcaption>Each pass visits one item and updates the total.</figcaption>
</figure>

A loop that never stops is stopped by the box after a few seconds, so you can try things safely.

## What You Will Learn

1. `for`, `while` and `do...while` loops.
2. `for...in` for the keys of an object.
3. `for...of` for the values of an array or string.
4. `break` and `continue`.

## For Loop

Use `for` when you know how many times to repeat.

`for (start; condition; step)`: start once, check before each pass, step after each pass.

```js runnable title="Printing five ticket numbers with one for loop"
for (let i = 1; i <= 5; i++) {
  console.log("Ticket", i);
}
```

Expected output:

```text
Ticket 1
Ticket 2
Ticket 3
Ticket 4
Ticket 5
```

The counter is often an index into an array. Stop at `i < cart.length`:

```js runnable title="Using the counter as an index into an array"
const cart = ["Pen", "Notebook", "Lunch box"];
for (let i = 0; i < cart.length; i++) {
  console.log(i + 1 + ".", cart[i]);
}
```

Expected output:

```text
1. Pen
2. Notebook
3. Lunch box
```

## While Loop

Use `while` when you do not know how many passes you need. It checks the condition **before** each pass.

```js runnable title="Saving 150 each month until the savings reach 1000"
let savings = 0;
let months = 0;
while (savings < 1000) {
  savings += 150;
  months++;
}
console.log(months, "months, saved", savings);
```

Expected output:

```text
7 months, saved 1050
```

Something inside must change the condition, or the loop never ends:

```js
// Not runnable, on purpose: savings never changes,
// so savings < 1000 is true forever.
let savings = 0;
while (savings < 1000) {
  console.log("Still saving...");
}
```

## Do While Loop

`do...while` runs the block **first**, then checks. So it always runs at least once.

```js runnable title="The same false condition in while and do...while"
let stock = 0;
while (stock > 0) {
  console.log("while: selling one");
}
do {
  console.log("do...while: ran once anyway");
} while (stock > 0);
```

Expected output:

```text
do...while: ran once anyway
```

## For In Loop

`for...in` gives the **keys** of an object. Read the value with `object[key]`.

```js runnable title="Listing every key and value of one customer object"
const customer = { name: "Asha", city: "Pune", orders: 3 };
for (const key in customer) {
  console.log(key, "=", customer[key]);
}
```

Expected output:

```text
name = Asha
city = Pune
orders = 3
```

`for...in` also visits inherited keys. To get only the object's own keys, use `for (const key of Object.keys(obj))`.

On an array, `for...in` gives index **strings**. Use `for...of` for arrays instead.

```js runnable title="for...in on an array gives the index as a string"
const sizes = ["S", "M"];
for (const i in sizes) {
  console.log(i, typeof i);
}
```

Expected output:

```text
0 string
1 string
```

## For Of Loop

`for...of` gives each **value** directly. No index to manage.

```js runnable title="Adding up a cart with for...of"
const prices = [120, 80, 45];
let total = 0;
for (const price of prices) {
  total += price;
}
console.log("Total:", total);
```

Expected output:

```text
Total: 245
```

It works on strings too, one character at a time:

```js runnable title="for...of over a string gives one character at a time"
for (const letter of "SALE") {
  console.log(letter);
}
```

Expected output:

```text
S
A
L
E
```

## Break Statement

`break` leaves the whole loop at once.

```js runnable title="Stopping at the first order over 500"
const totals = [250, 180, 640, 900];
for (const total of totals) {
  if (total > 500) {
    console.log("First big order:", total);
    break;
  }
  console.log("Checked", total);
}
```

Expected output:

```text
Checked 250
Checked 180
First big order: 640
```

## Continue Statement

`continue` skips the rest of **this pass** and moves to the next one.

```js runnable title="Skipping the items that are out of stock"
const items = [
  { name: "Pen", stock: 10 },
  { name: "Bag", stock: 0 },
  { name: "Mug", stock: 4 },
];
for (const item of items) {
  if (item.stock === 0) continue;
  console.log("Show", item.name);
}
```

Expected output:

```text
Show Pen
Show Mug
```

## Loops on a Web Page

Build one `<li>` per product with `for...of`. Skip sold-out items with `continue`, and count the rest.

```js runnable preview="product-list" title="Drawing a product list with a loop"
const products = [
  { name: "Steel bottle", price: 299, stock: 8 },
  { name: "Lunch box", price: 349, stock: 0 },
  { name: "Notebook", price: 60, stock: 25 },
  { name: "Pencil box", price: 120, stock: 3 },
];
const list = document.querySelector("#products");
let shown = 0;

for (const product of products) {
  if (product.stock === 0) continue;
  const li = document.createElement("li");
  li.textContent = `${product.name} — ₹${product.price}`;
  list.append(li);
  shown++;
}

document.querySelector("#status").textContent = `${shown} of ${products.length} products in stock`;
console.log("rows drawn:", shown);
```

Add a fifth product to the array and run again. The page grows with no new loop code.

**Easy way to remember:** for**...of** = values **of** a list. for**...in** = keys **in** an object.

## TL;DR

- `for` when you know the count; `while` when you do not.
- `do...while` always runs at least once.
- `for...of` gives values; `for...in` gives keys.
- `break` leaves the loop; `continue` skips one pass.
- Always change something that ends the loop.

## Try this

In the first `for` loop, change `i <= 5` to `i < 5`. Now you get only 4 tickets. Off-by-one mistakes hide in that one character.

## Check Yourself

## Common mistakes

| Mistake | Wrong idea | Correct idea | What goes wrong |
|---|---|---|---|
| `i <= cart.length` | The last index is the length | The last index is `length - 1` | An extra `undefined` pass |
| Not changing the `while` variable | The loop ends by itself | Something must make the condition false | The loop never stops |
| `for...in` on an array | It gives values | It gives index strings | `"0"`, `"1"` instead of items |
| `for...of` on a plain object | Objects are lists | Plain objects are not iterable | `TypeError: customer is not iterable` |
| `continue` when you meant `break` | Both stop the loop | `continue` skips one pass only | The loop keeps going |

## Quick reference

<div className="tscroll">

| Syntax | Meaning |
|---|---|
| `for (let i = 0; i < n; i++) { ... }` | repeat `n` times with a counter: start, check, update |
| `while (condition) { ... }` | check first, then repeat while the condition is true |
| `do { ... } while (condition);` | run once, then repeat while the condition is true |
| `for (const key in object) { ... }` | walk through the **keys** of an object |
| `for (const value of array) { ... }` | walk through the **values** of an array or string |
| `break;` | leave the loop straight away |
| `continue;` | skip the rest of this pass and go to the next one |

</div>

## Exercises

## What to Remember

- A loop repeats work for each item.
- Pick the loop by what you know: a count, a condition, or a list.
- `break` and `continue` control the flow inside.

Next: **Function Basics**. Give a piece of code a name, and reuse it.
