JavaScript Loops
Loops are used to repeat a block of code multiple times until a certain condition is met. Without loops, repetitive tasks would require writing the same code over and over. Loops make programs efficient and concise.
Real-life analogy: Imagine printing 100 tickets — instead of printing one by one manually, a loop automates the process.
Types of Loops in JavaScript
- for — Best when the number of repetitions is known
- while — Best when the repetitions depend on a condition
- do...while — Same as while, but always runs at least once
- for...of — Iterates over array elements
- for...in — Iterates over object properties
The for Loop
The for loop is the most commonly used loop. It consists of three parts: initialization, condition, and update.
Syntax:
for (initialization; condition; update) {
// Code to repeat
}for (let i = 1; i <= 5; i++) {
console.log("Count:", i);
}
// Output:
// Count: 1
// Count: 2
// Count: 3
// Count: 4
// Count: 5How the for Loop Works
- Initialization —
let i = 1— Runs once at the start. Sets up a counter variable. - Condition —
i <= 5— Checked before each iteration. If true, the loop runs. If false, the loop stops. - Update —
i++— Runs after each iteration. Increments the counter.
Counting Down
for (let i = 5; i >= 1; i--) {
console.log(i);
}
// Output: 5, 4, 3, 2, 1Looping Through an Array
let fruits = ["Apple", "Banana", "Cherry", "Mango"];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
// Output: Apple, Banana, Cherry, MangoThe while Loop
The while loop keeps executing a block of code as long as a condition remains true. It is used when the number of iterations is not known in advance.
Syntax:
while (condition) {
// Code to repeat
}let count = 1;
while (count <= 5) {
console.log("Step:", count);
count++; // Important! Without this, the loop runs forever
}
// Output: Step: 1, Step: 2, Step: 3, Step: 4, Step: 5Practical while Loop Example
// Keep asking to top up until balance is enough
let balance = 200;
let requiredAmount = 500;
while (balance < requiredAmount) {
console.log("Balance is low. Adding 100...");
balance += 100;
}
console.log("Final Balance:", balance);
// Output:
// Balance is low. Adding 100...
// Balance is low. Adding 100...
// Balance is low. Adding 100...
// Final Balance: 500The do...while Loop
The do...while loop is similar to while, but it guarantees the code block runs at least once — even if the condition is false from the start. The condition is checked after the block runs.
Syntax:
do {
// Code runs at least once
} while (condition);let number = 10;
do {
console.log("Number is:", number);
number++;
} while (number < 5);
// Output: Number is: 10
// (Runs once even though 10 < 5 is false)Practical do...while Example
// Show a welcome message at least once
let attempts = 0;
do {
console.log("Showing welcome message...");
attempts++;
} while (attempts < 1);
// Output: Showing welcome message... (runs exactly once)The for...of Loop
The for...of loop is the cleanest way to iterate over arrays (and other iterable objects like strings). It directly gives each element without needing an index.
let colors = ["Red", "Green", "Blue"];
for (let color of colors) {
console.log(color);
}
// Output: Red, Green, Bluefor...of with Strings
let word = "Hello";
for (let char of word) {
console.log(char);
}
// Output: H, e, l, l, oThe for...in Loop
The for...in loop iterates over the properties (keys) of an object.
let person = {
name: "Neha",
age: 28,
city: "Pune"
};
for (let key in person) {
console.log(key + ":", person[key]);
}
// Output:
// name: Neha
// age: 28
// city: PuneLoop Control Statements
break — Exit the Loop Early
The break statement immediately stops the loop, regardless of the condition.
for (let i = 1; i <= 10; i++) {
if (i === 5) {
break; // Stop when i reaches 5
}
console.log(i);
}
// Output: 1, 2, 3, 4continue — Skip Current Iteration
The continue statement skips the rest of the current iteration and jumps to the next one.
for (let i = 1; i <= 10; i++) {
if (i % 2 === 0) {
continue; // Skip even numbers
}
console.log(i);
}
// Output: 1, 3, 5, 7, 9 (only odd numbers)Nested Loops
A loop inside another loop is called a nested loop. The inner loop completes all its iterations for each single iteration of the outer loop.
// Print a multiplication table
for (let i = 1; i <= 3; i++) {
for (let j = 1; j <= 3; j++) {
console.log(i + " x " + j + " = " + (i * j));
}
}
// Output:
// 1 x 1 = 1
// 1 x 2 = 2
// 1 x 3 = 3
// 2 x 1 = 2
// ... and so onInfinite Loops — What to Avoid
An infinite loop runs forever and freezes the browser. Always ensure the loop has a valid exit condition.
// DANGER: This never stops!
// while (true) {
// console.log("Running forever...");
// }
// SAFE: Has an exit condition
let x = 0;
while (x < 5) {
console.log(x);
x++; // Condition will eventually become false
}Choosing the Right Loop
| Situation | Best Loop |
|---|---|
| Known number of iterations | for |
| Unknown iterations, condition-based | while |
| Must run at least once | do...while |
| Loop over array elements | for...of |
| Loop over object properties | for...in |
Practical Example — Sum of Numbers
// Calculate the sum of numbers from 1 to 100
let sum = 0;
for (let i = 1; i <= 100; i++) {
sum += i;
}
console.log("Sum of 1 to 100:", sum);
// Output: Sum of 1 to 100: 5050Key Points to Remember
- A
forloop has three parts: initialization, condition, and update - A
whileloop runs as long as the condition is true - A
do...whileloop always executes at least once for...ofis the cleanest way to loop through arraysfor...inis used to loop through object propertiesbreakexits the loop immediatelycontinueskips the current iteration and moves to the next- Always ensure a loop has a proper exit condition to avoid infinite loops
