Loops are used to execute a block of code repeatedly until a condition becomes false.
| Loop Type | Purpose | Example |
|---|---|---|
| for loop | Repeat code a fixed number of times | for(i=0; i<5; i++) |
| while loop | Repeat while condition is true | while(i<5) |
| do...while loop | Run code at least once | do{}while(i<5) |
| for...in loop | Loop through object properties | for(key in obj) |
| for...of loop | Loop through array values | for(value of arr) |
1. for Loop
Used when the number of iterations is known.
Syntax:
for(initialization; condition; increment/decrement){
// code
}
Example:
for(let i = 1; i <= 5; i++){
console.log(i);
}
Output:
1 2 3 4 5
2. while Loop:
Runs while the condition is true.
Syntax:
while(condition){
// code
}
Example:
let i = 1;
while(i <= 5){
console.log(i);
i++;
}
3. do...while Loop:
Executes code at least one time.
Syntax:
do{
// code
}while(condition);
Example:
let i = 1;
do{
console.log(i);
i++;
}while(i <= 5);
4. for Loop
Used for object properties.
Example:
let student = {
name: "John",
age: 20
};
for(let key in student){
console.log(key);
}
Output:
name age
5. for...of Loop
Used for arrays and iterable values.
Example:
let numbers = [10,20,30];
for(let value of numbers){
console.log(value);
}
Output:
10 20 30
Important Points
- Loops reduce repetitive code.
- for loop is commonly used.
- while loop checks condition first.
- do...while runs at least once.
- for...in is used for objects.
- for...of is used for arrays.