| JavaScript-Conditionals :👈 | 👉:JavaScript: Break & Continue |
JavaScript Loops (for, while, do…while) |
📘 JavaScript Loops (for, while, do…while)
Loops are the backbone of repetition in JavaScript. Also in any programming language. They let you run a block of code multiple times until a condition is met. Let’s go through the three main loops: for, while, and do…while.
1️⃣ for Loop
The for loop is used when you know how many times you want to run the code.
It has 3 parts: initialization, condition, and increment/decrement.
// Print numbers 1 to 5
for (let i = 1; i <= 5; i++) {
console.log(i);
}
// Output: 1 2 3 4 5
2️⃣ while Loop
The while loop runs as long as the condition is true.
It’s useful when the number of iterations is not known in advance.
// Print numbers 1 to 5
let j = 1;
while (j <= 5) {
console.log(j);
j++;
}
// Output: 1 2 3 4 5
3️⃣ do…while Loop
The do…while loop is similar to while,
but it always runs the code block at least once, even if the condition is false.
// Print numbers 1 to 5
let k = 1;
do {
console.log(k);
k++;
} while (k <= 5);
// Output: 1 2 3 4 5
✅ Quick Recap
- for → Best when you know the exact number of iterations.
- while → Best when you don’t know how many times, but have a condition.
- do…while → Always runs at least once, then checks the condition.
- Always ensure the loop has a termination condition to avoid infinite loops.
📌 Mini Project: Sum of Numbers
// Calculate sum of numbers 1 to 5 using a for loop
let sum = 0;
for (let i = 1; i <= 5; i++) {
sum += i;
}
console.log("Sum = " + sum); // Sum = 15
📘 Best Practices for Using Loops in JavaScript
- Choose the right loop type: Use
forwhen the number of iterations is known,whileordo…whilewhen it depends on a condition. -
Avoid infinite loops: Ensure loop conditions will eventually become false.
let i = 0; while(i < 5) { console.log(i); i++; // ensures termination } - Minimize work inside the loop: Precompute values outside the loop if possible.
-
Use descriptive variable names:
for(let index = 0; index < items.length; index++) { ... } -
Break early if possible:
for(let i = 0; i < arr.length; i++) { if(arr[i] === target) break; } -
Use continue wisely:
for(let i = 0; i < arr.length; i++) { if(arr[i] === null) continue; console.log(arr[i]); } - Consider array methods for iteration:
forEach,map,filter,reduce. - Avoid modifying loop counters inside the loop body: Keeps behavior predictable.
- Optimize nested loops: Minimize nesting to prevent performance issues.
- Keep loops readable: Break complex logic into separate functions.
| JavaScript-Conditionals :👈 | 👉:JavaScript: Break & Continue |