Loops
Introduction
Section titled “Introduction”Loops repeat a block of code until a condition is met. JavaScript has several loop types: for, while, and do-while.
for Loop
Section titled “for Loop”for (initialization; condition; increment) { // body}
for (let i = 0; i < 5; i++) { console.log(i); // 0, 1, 2, 3, 4}while Loop
Section titled “while Loop”let i = 0;while (i < 5) { console.log(i); // 0, 1, 2, 3, 4 i++;}do-while Loop
Section titled “do-while Loop”let i = 0;do { console.log(i); // 0, 1, 2, 3, 4 i++;} while (i < 5);Visual Explanation
Section titled “Visual Explanation”flowchart TD For["for (let i=0; i<5; i++)"] Check{"i < 5?"} Body["console.log(i)"] Inc["i++"] End["Loop ends"]
For --> Check Check -->|Yes| Body Body --> Inc Inc --> Check Check -->|No| EndLoop Comparison
Section titled “Loop Comparison”| Loop | Use Case | Condition Check |
|---|---|---|
for | Known number of iterations | Before each iteration |
while | Unknown iterations | Before each iteration |
do-while | Must run at least once | After each iteration |
Iterating Arrays
Section titled “Iterating Arrays”const fruits = ['apple', 'banana', 'orange'];
// Classic forfor (let i = 0; i < fruits.length; i++) { console.log(fruits[i]);}
// for...of (ES6)for (const fruit of fruits) { console.log(fruit);}
// forEachfruits.forEach(fruit => console.log(fruit));Summary
Section titled “Summary”for— known iteration countwhile— unknown count, checked beforedo-while— runs at least once- Prefer
for...offor arrays (ES6)