JavaScript 13 🧬 loops part 1
Loops are used to execute a block of code repeatedly under certain conditions. They allow you to perform tasks multiple times without writing the same code over and over again manually.
A Quick Look at the Examples
// 1. Basic for loop
for (let i = 0; i < 5; i++) {
console.log(i); // 0, 1, 2, 3, 4
}
// 2. Loop through an array
let fruits = ['apple', 'banana', 'cherry'];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]); // apple, banana, cherry
}
// 3. Nested loop (3×3 grid)
for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
console.log(`i: ${i}, j: ${j}`);
}
}
// 4. break statement
for (let i = 0; i < 10; i++) {
if (i === 5) break;
console.log(i); // 0, 1, 2, 3, 4
}
// 5. while loop
let i = 0;
while (i < 5) {
console.log(i); // 0, 1, 2, 3, 4
i++;
}
// 6. Countdown timer
let count = 10;
while (count > 0) {
console.log(`Countdown: ${count}`);
count--;
}
console.log('Go!');
// 7. do...while loop
let userInput;
do {
userInput = prompt("Please enter your name:");
} while (userInput === null || userInput.trim() === "");
console.log(`Hello, ${userInput}!`);
a. Loops Introduction
Loops are used to execute a block of code repeatedly under certain conditions. They allow you to perform tasks multiple times without writing the same code over and over again manually.
Common Uses and Benefits
| Use | Description |
|---|---|
| Iterating Over Collections | Process each item in an array or object |
| Repeating Actions | Run the same code multiple times |
| Controlling Program Flow | Skip, break, or continue based on conditions |
Loop Types in JavaScript
| Loop | Best For |
|---|---|
for | Known number of iterations |
while | Unknown number, condition-based |
do...while | At least one iteration guaranteed |
for...in | Iterating object properties |
for...of | Iterating iterable values (arrays, strings) |
b. The for Loop
The for loop is used when you know exactly how many times you want to run the loop.
Syntax
for (initialization; condition; final-expression) {
// code block to be executed
}
The Three Expressions
| Expression | When It Runs | Purpose |
|---|---|---|
| Initialization | Once, before the loop starts | Declare and initialize the counter |
| Condition | Before each iteration | If true, run the block; if false, exit |
| Final-expression | After each iteration | Increment/decrement the counter |
Execution Order
1. Initialization (once)
2. Condition check → if true
3. Loop body
4. Final-expression
5. Back to step 2
Example 1: Print 0 to 4
for (let i = 0; i < 5; i++) {
console.log(i); // 0, 1, 2, 3, 4
}
Step-by-step:
i = 0(initialization)0 < 5→ true → log0i++→i = 11 < 5→ true → log1- … continues until
i = 5 5 < 5→ false → exit
Example 2: Loop Through an Array
let fruits = ['apple', 'banana', 'cherry'];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
// apple
// banana
// cherry
Key point: fruits.length gives the number of items, so the loop runs exactly that many times.
Example 3: Nested Loop (3×3 Grid)
for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
console.log(`i: ${i}, j: ${j}`);
}
}
Output:
i: 0, j: 0
i: 0, j: 1
i: 0, j: 2
i: 1, j: 0
i: 1, j: 1
i: 1, j: 2
i: 2, j: 0
i: 2, j: 1
i: 2, j: 2
How it works: For each value of i, the inner loop runs completely (3 times).
The break Statement
Terminates the loop prematurely when a condition is met.
for (let i = 0; i < 10; i++) {
if (i === 5) break;
console.log(i); // 0, 1, 2, 3, 4
}
When i === 5: The loop stops immediately — no further iterations.
The continue Statement
Skips the current iteration and moves to the next.
for (let i = 0; i < 5; i++) {
if (i === 2) continue;
console.log(i); // 0, 1, 3, 4 (skips 2)
}
c. while and do…while Loops
The while Loop
Repeatedly executes a block of code as long as a condition is true.
while (condition) {
// Code block to be executed while the condition is true
}
Example 1: Print 0 to 4
let i = 0;
while (i < 5) {
console.log(i); // 0, 1, 2, 3, 4
i++; // Don't forget this — or infinite loop!
}
Example 2: Countdown Timer
let count = 10;
while (count > 0) {
console.log(`Countdown: ${count}`);
count--;
}
console.log('Go!');
Key Point: The condition is checked before each iteration. If it’s false initially, the loop body never runs.
The do...while Loop
Similar to while, but with one key difference: it guarantees at least one execution before checking the condition.
do {
// Code block to be executed
} while (condition);
Example: Ensure Valid User Input
let userInput;
do {
userInput = prompt("Please enter your name:");
} while (userInput === null || userInput.trim() === "");
console.log(`Hello, ${userInput}!`);
How it works:
- Ask for input
- Check if it’s
null(cancelled) or empty - If invalid, ask again
- Repeat until valid input is provided
Key Point: The body runs at least once, even if the condition is false from the start.
while vs do…while
| Aspect | while | do...while |
|---|---|---|
| Condition check | Before body | After body |
| Minimum runs | 0 | 1 |
| Best for | Unknown iterations | At-least-once scenarios |
Visual comparison:
while: do...while:
1. Check condition 1. Run body
2. If true → run body 2. Check condition
3. Repeat 3. If true → repeat
(May run 0 times) (Always runs at least once)
Complete Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Loops — Part 1</title>
<style>
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
max-width: 800px;
margin: 0 auto;
padding: 20px;
background: #f8f9fa;
color: #333;
line-height: 1.6;
}
h1 { color: #007bff; border-bottom: 3px solid #007bff; padding-bottom: 10px; }
h2 { color: #28a745; border-left: 4px solid #28a745; padding-left: 15px; margin-top: 30px; }
.demo-box {
background: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
margin: 15px 0;
}
pre {
background: #1e1e1e;
color: #d4d4d4;
padding: 15px;
border-radius: 8px;
overflow-x: auto;
font-family: 'Courier New', monospace;
font-size: 0.9rem;
line-height: 1.8;
}
.keyword { color: #569cd6; }
.string { color: #ce9178; }
.number { color: #b5cea8; }
.function { color: #dcdcaa; }
.comment { color: #6a9955; }
.boolean { color: #569cd6; }
#output {
background: #e9ecef;
padding: 15px;
border-radius: 8px;
margin-top: 15px;
min-height: 40px;
font-family: 'Courier New', monospace;
font-size: 0.85rem;
border-left: 4px solid #007bff;
white-space: pre-wrap;
}
.btn {
padding: 10px 20px;
background: #007bff;
color: white;
border: none;
border-radius: 6px;
font-size: 1em;
font-weight: bold;
cursor: pointer;
margin: 5px;
transition: all 0.3s;
}
.btn:hover {
background: #0056b3;
transform: translateY(-2px);
}
.btn-danger { background: #dc3545; }
.btn-danger:hover { background: #a71d2a; }
.btn-success { background: #28a745; }
.btn-success:hover { background: #1e7e34; }
table {
width: 100%;
border-collapse: collapse;
margin: 15px 0;
}
th, td {
padding: 10px;
border: 1px solid #ddd;
text-align: left;
}
th { background: #007bff; color: white; }
tr:nth-child(even) { background: #f8f9fa; }
</style>
</head>
<body>
<h1>Loops — Part 1</h1>
<div class="demo-box">
<h2>1. Basic for Loop</h2>
<pre>
<span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i < <span class="number">5</span>; i++) {
console.log(i); <span class="comment">// 0, 1, 2, 3, 4</span>
}
</pre>
</div>
<div class="demo-box">
<h2>2. Loop Through an Array</h2>
<pre>
<span class="keyword">let</span> fruits = [<span class="string">'apple'</span>, <span class="string">'banana'</span>, <span class="string">'cherry'</span>];
<span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i < fruits.length; i++) {
console.log(fruits[i]);
}
</pre>
</div>
<div class="demo-box">
<h2>3. Nested Loop (3×3 Grid)</h2>
<pre>
<span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i < <span class="number">3</span>; i++) {
<span class="keyword">for</span> (<span class="keyword">let</span> j = <span class="number">0</span>; j < <span class="number">3</span>; j++) {
console.log(<span class="string">`i: ${i}, j: ${j}`</span>);
}
}
</pre>
</div>
<div class="demo-box">
<h2>4. break and continue</h2>
<pre>
<span class="comment">// break — exits the loop entirely</span>
<span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i < <span class="number">10</span>; i++) {
<span class="keyword">if</span> (i === <span class="number">5</span>) <span class="keyword">break</span>;
console.log(i); <span class="comment">// 0, 1, 2, 3, 4</span>
}
<span class="comment">// continue — skips the current iteration</span>
<span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i < <span class="number">5</span>; i++) {
<span class="keyword">if</span> (i === <span class="number">2</span>) <span class="keyword">continue</span>;
console.log(i); <span class="comment">// 0, 1, 3, 4</span>
}
</pre>
</div>
<div class="demo-box">
<h2>5. while Loop</h2>
<pre>
<span class="keyword">let</span> i = <span class="number">0</span>;
<span class="keyword">while</span> (i < <span class="number">5</span>) {
console.log(i); <span class="comment">// 0, 1, 2, 3, 4</span>
i++;
}
<span class="keyword">let</span> count = <span class="number">10</span>;
<span class="keyword">while</span> (count > <span class="number">0</span>) {
console.log(<span class="string">`Countdown: ${count}`</span>);
count--;
}
console.log(<span class="string">'Go!'</span>);
</pre>
</div>
<div class="demo-box">
<h2>6. do...while Loop</h2>
<pre>
<span class="keyword">let</span> userInput;
<span class="keyword">do</span> {
userInput = prompt(<span class="string">"Please enter your name:"</span>);
} <span class="keyword">while</span> (userInput === <span class="boolean">null</span> || userInput.trim() === <span class="string">""</span>);
console.log(<span class="string">`Hello, ${userInput}!`</span>);
</pre>
</div>
<div class="demo-box">
<h2>7. Interactive: Countdown</h2>
<button class="btn" onclick="startCountdown()">Start Countdown</button>
<div id="countdownOutput"></div>
</div>
<div class="demo-box">
<h2>8. Interactive: Multiplication Table</h2>
<button class="btn btn-success" onclick="showMultiplicationTable()">Show 5× Table</button>
<div id="tableOutput"></div>
</div>
<div class="demo-box">
<h2>9. Live Output — All Examples</h2>
<div id="output">Loading...</div>
</div>
<script>
// ============================================
// Loops — Live Demo
// ============================================
let results = [];
// 1. Basic for loop
results.push('📌 Basic for Loop:\n');
let basicLoop = [];
for (let i = 0; i < 5; i++) {
basicLoop.push(i);
}
results.push(' for (let i = 0; i < 5; i++) → [' + basicLoop.join(', ') + ']');
results.push('');
// 2. Loop through an array
results.push('📌 Loop Through an Array:\n');
let fruits = ['apple', 'banana', 'cherry'];
for (let i = 0; i < fruits.length; i++) {
results.push(' fruits[' + i + '] → ' + fruits[i]);
}
results.push('');
// 3. Nested loop
results.push('📌 Nested Loop (3×3 Grid):\n');
let nestedCount = 0;
for (let i = 0; i < 3; i++) {
let row = ' ';
for (let j = 0; j < 3; j++) {
row += `(${i},${j}) `;
nestedCount++;
}
results.push(row);
}
results.push(' Total iterations: ' + nestedCount);
results.push('');
// 4. break statement
results.push('📌 break Statement:\n');
let breakResult = [];
for (let i = 0; i < 10; i++) {
if (i === 5) break;
breakResult.push(i);
}
results.push(' for (let i = 0; i < 10; i++) { if (i === 5) break; } → [' + breakResult.join(', ') + ']');
results.push('');
// 5. continue statement
results.push('📌 continue Statement:\n');
let continueResult = [];
for (let i = 0; i < 5; i++) {
if (i === 2) continue;
continueResult.push(i);
}
results.push(' for (let i = 0; i < 5; i++) { if (i === 2) continue; } → [' + continueResult.join(', ') + ']');
results.push('');
// 6. while loop
results.push('📌 while Loop:\n');
let whileResult = [];
let i = 0;
while (i < 5) {
whileResult.push(i);
i++;
}
results.push(' while (i < 5) → [' + whileResult.join(', ') + ']');
results.push('');
// 7. Countdown
results.push('📌 Countdown Timer:\n');
let count = 5;
let countdown = [];
while (count > 0) {
countdown.push('Countdown: ' + count);
count--;
}
countdown.push('Go!');
results.push(' ' + countdown.join('\n '));
results.push('');
// 8. do...while loop
results.push('📌 do...while Loop:\n');
results.push(' Runs at least once before checking the condition');
let doWhileCount = 0;
let doWhileResult = [];
do {
doWhileResult.push(doWhileCount);
doWhileCount++;
} while (doWhileCount < 3);
results.push(' do { } while (i < 3) → [' + doWhileResult.join(', ') + ']');
results.push('');
// 9. Comparison: while vs do...while
results.push('📌 while vs do...while (condition false initially):\n');
let whileTest = [];
let w = 10;
while (w < 5) {
whileTest.push(w);
w++;
}
results.push(' while (10 < 5) → runs ' + whileTest.length + ' times (condition false from start)');
let doWhileTest = [];
let dw = 10;
do {
doWhileTest.push(dw);
dw++;
} while (dw < 5);
results.push(' do { } while (10 < 5) → runs ' + doWhileTest.length + ' time(s) (always runs once)');
results.push('');
// 10. Practical: Sum of numbers
results.push('📌 Practical: Sum of Numbers:\n');
let sum = 0;
for (let n = 1; n <= 10; n++) {
sum += n;
}
results.push(' Sum of 1 to 10 → ' + sum);
results.push('');
// 11. Practical: Reverse a string
results.push('📌 Practical: Reverse a String:\n');
let original = "hello";
let reversed = "";
for (let k = original.length - 1; k >= 0; k--) {
reversed += original[k];
}
results.push(' "' + original + '" → "' + reversed + '"');
results.push('');
// 12. Infinite loop warning
results.push('📌 ⚠️ Infinite Loop Warning:\n');
results.push(' If the condition never becomes false, the loop runs forever!');
results.push(' Always ensure the loop variable changes each iteration.');
document.getElementById('output').textContent = results.join('\n');
// ============================================
// Interactive Functions
// ============================================
function startCountdown() {
const output = document.getElementById('countdownOutput');
let output_text = '';
let count = 5;
while (count > 0) {
output_text += `Countdown: ${count}<br>`;
count--;
}
output_text += '🚀 Go!';
output.innerHTML = output_text;
}
function showMultiplicationTable() {
const output = document.getElementById('tableOutput');
let output_text = '<strong>5× Multiplication Table</strong><br>';
for (let i = 1; i <= 10; i++) {
output_text += `5 × ${i} = ${5 * i}<br>`;
}
output.innerHTML = output_text;
}
// Run initial countdown
startCountdown();
</script>
</body>
</html>
Quick Reference
Loop Types
| Loop | Syntax | Best For |
|---|---|---|
for | for (init; cond; final) { } | Known number of iterations |
while | while (cond) { } | Unknown iterations |
do...while | do { } while (cond); | At least one iteration |
for Loop Expressions
| Expression | When It Runs | Purpose |
|---|---|---|
| Initialization | Once before the loop | Declare counter |
| Condition | Before each iteration | Continue or stop |
| Final-expression | After each iteration | Increment/decrement |
break vs continue
| Statement | Effect |
|---|---|
break | Exits the loop entirely |
continue | Skips the current iteration only |
while vs do…while
| Aspect | while | do...while |
|---|---|---|
| Condition check | Before body | After body |
| Minimum runs | 0 | 1 |
| Best for | Unknown iterations | At-least-once scenarios |
Best Practices
✅ Do This:
// Cache the array length in the loop condition
for (let i = 0, len = arr.length; i < len; i++) { }
// Use for...of for simple array iteration (cleaner)
for (const fruit of fruits) { }
// Ensure the loop variable changes
let i = 0;
while (i < 10) {
i++; // Don't forget this!
}
// Use break for early exit
for (let i = 0; i < arr.length; i++) {
if (arr[i] === target) {
console.log("Found!");
break;
}
}
// Use do...while for retry logic
do {
result = tryOperation();
} while (!result.success);
❌ Don’t Do This:
// Don't create infinite loops
while (true) {
// No break or condition change — runs forever!
}
// Don't modify the counter inside the loop body
for (let i = 0; i < 10; i++) {
i += 2; // Confusing — skips iterations!
}
// Don't use for...in for arrays
for (let i in arr) { } // Iterates indices as strings
// Don't use off-by-one errors
for (let i = 0; i <= arr.length; i++) { } // ❌ arr[arr.length] is undefined!
// Use i < arr.length instead
// Don't declare variables inside the loop body
for (let i = 0; i < 10; i++) {
let x = i * 2; // Recreated each iteration — move outside if reused
}
Common Pitfalls
| Pitfall | Problem | Solution |
|---|---|---|
| Infinite loop | Condition never false | Ensure loop variable changes |
| Off-by-one | <= vs < | Use < for 0-based arrays |
Forgetting i++ | Infinite loop | Always increment |
| Modifying counter inside | Skips iterations | Don’t reassign i |
Using for...in for arrays | Returns strings | Use for...of or classic for |
break/continue confusion | Wrong loop behavior | Remember: break exits, continue skips |
Pro Tip: Use a for loop when you know the number of iterations, while when the count is unknown, and do...while when the code must run at least once (like user input validation). Always ensure your loop variable changes each iteration — otherwise you’ll create an infinite loop that freezes the browser. Remember: break exits the loop entirely, while continue skips to the next iteration. And for arrays, use for...of for cleaner syntax than the classic for loop!
Stop using slow, ad-bloated tool sites! 🤮
🔎 Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)
⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free
🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!