Loops in JavaScript

ยท

3 min read

What is loops?

Loops in JavaScript allow you to repeatedly execute a block of code as long as a specified condition is true.

Types of loops:

1. For Loop

The for loop repeats a block of code a specific number of times, typically when you know how many iterations are needed.

for (initialization; condition; increment/decrement) {
  // Code to be executed
}

Example:

let num = 5, table
for(let i=1; i<=10 ; i++){
    table = i * num 
    console.log(table);
}

Explanation:

  • initialization: Initializes a counter variable (i = 1).

  • condition: Runs the loop while i < 10.

  • increment/decrement: Increases i by 1 each iteration (i++).

2. While Loop

The while loop executes a block of code as long as the specified condition is true.

while (condition) {
  // Code to be executed
}

Example:

let i = 1
while(i<=10){
     console.log(i)
     i++
}

3. Do...While Loop

The do...while loop is similar to the while loop, but it always runs the code block at least once, even if the condition is false at the start.

do {
  // Code to be executed
} while (condition);

Example:

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

Explanation:

  • The code block executes once before checking the condition.

4. For...In Loop

The for...in loop iterates over the properties of an object (or the indices of an array).

for (key in object) {
  // Code to be executed
}

Example:

let person = {name: "John", age: 30, city: "New York"};
for (let key in person) {
  console.log(key + ": " + person[key]);
}

Explanation:

  • This loop iterates over each key in the person object and prints the key-value pairs.

5. For...Of Loop

The for...of loop is used to iterate over the values of an iterable object like arrays, strings, etc.

for (value of iterable) {
  // Code to be executed
}

Example:

let numbers = [10, 20, 30];
for (let num of numbers) {
  console.log(num);
}

Explanation:

  • The loop iterates over each element of the numbers array and prints the values.

6. Break and Continue

  • break: Exits the loop immediately, regardless of the condition.

  • continue: Skips the rest of the current iteration and moves on to the next one.

Example using break:

for (let i = 0; i < 10; i++) {
  if (i === 5) {
    break;
  }
  console.log(i); // Stops printing when i is 5
}

Example using continue:

for (let i = 0; i < 10; i++) {
  if (i === 5) {
    continue;
  }
  console.log(i); // Skips printing 5
}
ย