Topic 5: Loops in JavaScript
Loops execute a block of code repeatedly while a condition is met. They save you from writing the same code over and over.
Without a loop:
console.log("Hello");
console.log("Hello");
console.log("Hello");
console.log("Hello");
console.log("Hello");Using a loop:
for (let i = 1; i <= 5; i++) {
console.log("Hello");
}Both produce the same output, but loops make code shorter and easier to maintain.
1. for Loop
A for loop is useful when you know how many times you want to run a block of code.
Syntax:
for (initialization; condition; update) {
// Code to execute
}The three parts are:
• Initialization sets the starting value.
• Condition checks whether the loop should continue.
• Update changes the variable after each iteration.
Example:
for (let i = 1; i <= 5; i++) {
console.log(i);
}Output:
1
2
3
4
5
Here, i starts at 1, increases by 1 after each iteration, and the loop ends when i <= 5 is false.
2. while Loop
A while loop runs as long as its condition is true. It’s useful when you don’t know exactly how many iterations are needed.
while (condition) {
// Code to execute
}let i = 1;
while (i <= 5) {
console.log(i);
i++;
}
The condition is checked before each iteration. Make sure the loop can eventually end, or it may run forever.
3.
do...while LoopA
do...while loop runs its code at least once before checking the condition.do {
// Code to execute
} while (condition);do {
console.log(i);
i++;
} while (i <= 5);Key difference:
•
for is commonly used when the number of iterations is known.•
while checks the condition before running the code.•
do...while runs the code once before checking the condition.4.
for...of LoopUse
for...of to iterate over values in iterables such as arrays, strings, maps, and sets.Example: iterating through an array:
let fruits = ["Apple", "Mango", "Banana"];
for (let fruit of fruits) {
console.log(fruit);
}
Apple
Mango
Banana
Example: iterating through a string:
let name = "JavaScript";
for (let character of name) {
console.log(character);
}
This prints each character separately.
5.
for...in LoopUse
for...in to iterate over an object's enumerable property keys.let student = {
name: "Rahul",
age: 22,
city: "Delhi"
};
for (let key in student) {
console.log(key, student[key]);
}name Rahul
age 22
city Delhi
key is the property name, and student[key] retrieves its value. For arrays, prefer for...of or array methods.6. Nested Loops
A nested loop is a loop inside another loop. It’s commonly used for patterns, matrices, and multidimensional arrays.
for (let i = 1; i <= 3; i++) {
for (let j = 1; j <= 3; j++) {
console.log(i, j);
}
}1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
