Loops are used to execute a block of code repeatedly until a condition becomes false.

Loop TypePurposeExample
for loopRepeat code a fixed number of timesfor(i=0; i<5; i++)
while loopRepeat while condition is truewhile(i<5)
do...while loopRun code at least oncedo{}while(i<5)
for...in loopLoop through object propertiesfor(key in obj)
for...of loopLoop through array valuesfor(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.