JavaScript Loops

In JavaScript, loops are used to execute a block of code repeatedly until a specified condition is met. There are several types of loops available:

1. for Loop:

The for loop repeats a block of code a specified number of times.

for (let i = 0; i < 5; i++) {
  console.log(i);
}

2. while Loop:

The while loop repeats a block of code while a specified condition is true.

let i = 0;
while (i < 5) {
  console.log(i);
  i++;
}

3. do…while Loop:

The do...while loop is similar to the while loop, but it executes the block of code at least once before checking the condition.

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

Loop Control Statements:

JavaScript provides loop control statements to control the flow of loops:

  • break: Terminates the loop immediately.
  • continue: Skips the current iteration of the loop and continues with the next iteration.
for (let i = 0; i < 10; i++) {
  if (i === 5) {
    break; // Exit the loop when i is 5
  }
  console.log(i);
}
for (let i = 0; i < 10; i++) {
  if (i === 5) {
    continue; // Skip iteration when i is 5
  }
  console.log(i);
}

Nested Loops:

You can nest loops within each other to perform more complex iterations.

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

Looping Through Arrays:

You can use loops to iterate over arrays and perform operations on each element.

let fruits = ['apple', 'banana', 'orange'];

for (let i = 0; i < fruits.length; i++) {
  console.log(fruits[i]);
}

forEach() Method:

The forEach() method is a built-in method for arrays that executes a provided function once for each array element.

fruits.forEach(function(fruit) {
  console.log(fruit);
});

Loops are essential for performing repetitive tasks and iterating over collections of data in JavaScript. Depending on the situation, you can choose the appropriate type of loop to achieve your desired outcome efficiently.