Building Your Learning Module...
Getting things ready for you!
Find videos you like?
Save to resource drawer for future reference!
Loops let you run the same code multiple times automatically. Instead of copying and pasting, write it once and let the loop repeat it!
// Printing 1 to 5 - repetitive! console.log(1); console.log(2); console.log(3); console.log(4); console.log(5); // What if we need 1 to 100? // We'd have to write 100 lines!
// Much cleaner!
for (let i = 1; i <= 5; i++) {
console.log(i);
}
// Works for 1 to 100 too!
// Just change 5 to 100for (let i = 0; i < 5; i++) { ... }let i = 0Start at 0 (initialization)
i < 5Keep going while i is less than 5 (condition)
i++Add 1 to i after each loop (increment)
Count, loop through arrays, repeat actions
while (condition) { ... }Keeps running as long as the condition is true. Be careful - if the condition never becomes false, you get an infinite loop!
Repeat until a condition is met
for (const item of array) { ... }Gets each item from the array automatically. No need for indexes!
The easiest way to loop through arrays
break;Exits the loop immediately. Use when you found what you're looking for!
continue;Skips the rest of current loop and goes to next iteration
Control loop flow with break and continue
Calculate total price using a loop
Use when you know how many times to repeat
Keep going until something becomes false
Simplest way to go through array items
Exit early when you find what you need