DEV Community

Anees Abdul
Anees Abdul

Posted on

Looping Statements in JavaScript!

What is a Loop?
A loop repeats a set of instructions until a condition is met.

Example:
Instead of writing console.log("Hello") 5 times, we can use a loop.

Types of Loops in JavaScript
JavaScript provides several types of loops:

  1. for loop
  2. while loop
  3. do...while loop
  4. for...of loop(To be discussed)
  5. for...in loop

1. for loop:

  • for loop is used to execute a block of code repeatedly, until a specified condition evaluates to false.
for (initialization; condition; increment/decrement) {
    // code to execute
}
Enter fullscreen mode Exit fullscreen mode

Best used when you know how many times to loop.

for (let i = 1; i <= 5; i++) {
    console.log("Hello " + i);
}
O/P: 
Hello 1
Hello 2
Hello 3
Hello 4
Hello 5
Enter fullscreen mode Exit fullscreen mode

2. while Loop:
The while loop runs as long as the condition is true.

while (condition) {
    // code
}
Enter fullscreen mode Exit fullscreen mode

Used when the number of iterations is not fixed.

let i = 1;

while (i <= 5) {
    console.log(i);
    i++;
}
O/P:
1
2
3
4
5
Enter fullscreen mode Exit fullscreen mode

3. do...while Loop:
This loop runs at least once, even if the condition is false.

do {
    // code
} while (condition);
Enter fullscreen mode Exit fullscreen mode

Useful when the code must run at least once.

let i = 1;

do {
    console.log(i);
    i++;
} while (i <= 5);
Enter fullscreen mode Exit fullscreen mode

4. for...of Loop:
Used to iterate over the values of arrays or strings.
Best for arrays and iterable objects.

let fruits = ["apple", "banana", "mango"];

for (let fruit of fruits) {
    console.log(fruit);
}
O/P:
apple
banana
mango
Enter fullscreen mode Exit fullscreen mode

5. for...in Loop:
Used to iterate over keys (properties) of an object.
Best for objects.

let person = {
    name: "Anees",
    age: 30
};

for (let key in person) {
    console.log(key + ": " + person[key]);
}
O/P:
name: Anees
age: 30

Enter fullscreen mode Exit fullscreen mode

Important Keywords:

  1. break
  2. continue

break: Stops the loop completely.

for (let i = 1; i <= 5; i++) {
    if (i === 3) break;
    console.log(i);
}
O/P:
1
2
Enter fullscreen mode Exit fullscreen mode

continue: Skips the current iteration.

for (let i = 1; i <= 5; i++) {
    if (i === 3) continue;
    console.log(i);
}
O/P:
1
2
4
5
Enter fullscreen mode Exit fullscreen mode

Advantages of Loops

  • Saves time and reduces code duplication
  • Makes code cleaner and readable
  • Handles repetitive tasks easily
  • Useful in arrays, objects, and automation

Top comments (0)