What Are JavaScript Loops? See Examples in detail

Loops are used in JavaScript to repeat a block of code multiple times until a certain condition is met. They help reduce redundancy and make your code more efficient.

This blog explains the different types of loops with examples.


⭐ 1. Why Use Loops?

Without loops, you would have to write repetitive code:

console.log("Hello");
console.log("Hello");
console.log("Hello");

With loops, the same task can be done in fewer lines:

for(let i = 0; i < 3; i++){
  console.log("Hello");
}

⭐ 2. The for Loop

The for loop is commonly used when you know how many times you want to repeat the code.

Syntax:

for(initialization; condition; increment/decrement){
   // code to run
}

Example:

for(let i = 1; i <= 5; i++){
  console.log("Number " + i);
}

⭐ 3. The while Loop

The while loop repeats as long as the condition is true. Use it when you don’t know how many iterations will be needed.

Syntax:

while(condition){
   // code to run
}

Example:

let i = 1;
while(i <= 5){
  console.log("Number " + i);
  i++;
}

⭐ 4. The do-while Loop

The do-while loop runs at least once and then checks the condition.

Syntax:

do {
   // code to run
} while(condition);

Example:

let i = 1;
do {
  console.log("Number " + i);
  i++;
} while(i <= 5);

⭐ 5. Loop Control Statements

break

Stops the loop immediately.

for(let i = 1; i <= 5; i++){
  if(i === 3) break;
  console.log(i);
}
// Output: 1, 2

continue

Skips the current iteration and continues with the next.

for(let i = 1; i <= 5; i++){
  if(i === 3) continue;
  console.log(i);
}
// Output: 1, 2, 4, 5

⭐ 6. Nested Loops

Loops can be placed inside other loops.

Example:

for(let i = 1; i <= 3; i++){
  for(let j = 1; j <= 2; j++){
    console.log(`i=${i}, j=${j}`);
  }
}

⭐ 7. Looping Through Arrays

for loop

let fruits = ["Apple", "Banana", "Mango"];
for(let i = 0; i < fruits.length; i++){
  console.log(fruits[i]);
}

for…of loop (ES6)

for(let fruit of fruits){
  console.log(fruit);
}

forEach method

fruits.forEach(fruit => console.log(fruit));

⭐ Conclusion

Loops are essential in JavaScript for reducing repetitive code and handling tasks dynamically. Understanding different types of loops and their control statements helps in building efficient programs.


📌 Citations

🔗 View other articles about Javascript:
https://savanka.com/category/learn/js/

🔗 External Javascript Documentation:
https://www.w3schools.com/js/

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *