๐
๐จ
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}45// Output:6// Count: 07// Count: 18// Count: 29// Count: 310// Count: 4
let i = 0Start at 0
i < 5Continue while true
i++Add 1 each time
๐ค
๐จ
Looping Through Arrays
Loops are great for going through arrays:
1const fruits = ["apple", "banana", "orange"];23// Classic for loop4for (let i = 0; i < fruits.length; i++) {5 console.log(fruits[i]);6}78// Modern for...of loop (cleaner!)9for (const fruit of fruits) {10 console.log(fruit);11}1213// Both output:14// apple15// banana16// orange
๐ก
๐จ
The while Loop
Use while when you don't know how many times to repeat:
1let count = 0;23while (count < 3) {4 console.log("Count is:", count);5 count++; // Don't forget this!6}78// Output:9// Count is: 010// Count is: 111// 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 early2for (let i = 0; i < 10; i++) {3 if (i === 5) break; // Stop at 54 console.log(i); // 0, 1, 2, 3, 45}67// continue - skip to next iteration8for (let i = 0; i < 5; i++) {9 if (i === 2) continue; // Skip 210 console.log(i); // 0, 1, 3, 411}
๐ฎ
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