๐Ÿ”

Loops

๐ŸŽ‰
๐Ÿ’จ
Loops let you repeat code without writing it over and over!

What are Loops?

Loops repeat a block of code multiple times. Instead of writing the same code 100 times, you write it once and let the loop do the work!

Think of it like a train going around a track - it keeps going until you tell it to stop.

๐Ÿ’ก
๐Ÿ’จ

The for Loop

The for loop is perfect when you know how many times to repeat:

1for (let i = 0; i < 5; i++) {
2 console.log("Count:", i);
3}
4
5// Output:
6// Count: 0
7// Count: 1
8// Count: 2
9// Count: 3
10// Count: 4
let i = 0
Start at 0
i < 5
Continue while true
i++
Add 1 each time
๐Ÿค”
๐Ÿ’จ

Looping Through Arrays

Loops are great for going through arrays:

1const fruits = ["apple", "banana", "orange"];
2
3// Classic for loop
4for (let i = 0; i < fruits.length; i++) {
5 console.log(fruits[i]);
6}
7
8// Modern for...of loop (cleaner!)
9for (const fruit of fruits) {
10 console.log(fruit);
11}
12
13// Both output:
14// apple
15// banana
16// orange
๐Ÿ’ก
๐Ÿ’จ

The while Loop

Use while when you don't know how many times to repeat:

1let count = 0;
2
3while (count < 3) {
4 console.log("Count is:", count);
5 count++; // Don't forget this!
6}
7
8// Output:
9// Count is: 0
10// Count is: 1
11// Count is: 2

โš ๏ธ Always make sure your loop will eventually stop, or it will run forever (infinite loop)!

๐Ÿค”
๐Ÿ’จ

break and continue

1// break - exit the loop early
2for (let i = 0; i < 10; i++) {
3 if (i === 5) break; // Stop at 5
4 console.log(i); // 0, 1, 2, 3, 4
5}
6
7// continue - skip to next iteration
8for (let i = 0; i < 5; i++) {
9 if (i === 2) continue; // Skip 2
10 console.log(i); // 0, 1, 3, 4
11}
๐ŸŽฎ

Try It Yourself!

Watch the loop run step by step! Adjust the count and click Run.

For Loop Visualizer

1for (let i = 0; i < 5; i++) {
2 console.log("Iteration " + i);
3}
// Output will appear here

๐Ÿงช Code Lab - Try It Yourself!

๐ŸงชLoops Lab
Enter RunShift+Enter New line History
๐Ÿ“‹Output

Run some code to see the output here!

๐Ÿ’กTry These Examples