1. Introduction

Loops are essential constructs in programming that allow you to execute a block of code repeatedly. They are particularly handy when you need to perform a task multiple times without writing the same code over and over again. JavaScript provides several types of loops, each serving different purposes. In this article, we'll explore various loop types in JavaScript with code examples for better understanding.

What Are Loops?

Loops are control structures that repeat a block of code until a specified condition evaluates to false. They help automate repetitive tasks and iterate over data structures like arrays and objects. The syntax of the while loop is as follows:

while(condition) {
    block of code
}

2. The while loop

The while loop executes a block of code while a specified condition is true. It continues iterating until the condition becomes false.

let count = 0;
while (count < 5) {
  console.log(count);
  count++;
}
// Output:
// 0
// 1
// 2
// 3
// 4

3. The do... while loop

Similar to the while loop, the do... while loop executes a block of code once before checking if the condition is true. It continues iterating as long as the condition remains true.

let i = 0;
do {
  console.log(i);
  i++;
} while (i < 5);
// Output:
// 0
// 1
// 2
// 3
// 4

4. The for loop

The for loop repeats a block of code a specified number of times. It consists of an initialization, a condition, and an iteration statement.

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

5. Loops and arrays

Loops are commonly used to iterate over arrays to access and manipulate their elements.

const numbers = [1, 2, 3, 4, 5];
for (let i = 0; i < numbers.length; i++) {
  console.log(numbers[i]);
}
// Output:
// 1
// 2
// 3
// 4
// 5

6. The for...of loop

The for...of loop provides a concise syntax for iterating over iterable objects like arrays.

const colors = ['red', 'green', 'blue'];
for (const color of colors) {
  console.log(color);
}
// Output:
// red
// green
// blue

7. The for...in loop

The for...in loop iterates over the enumerable properties of an object.

const person = {
  name: 'John',
  age: 30,
  gender: 'male'
};
for (const key in person) {
  console.log(`${key}: ${person[key]}`);
}
// Output:
// name: John
// age: 30
// gender: male

8. The break and continue statements

The break statement terminates the loop execution immediately when encountered. For instance:

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

The continue statement skips the current iteration of the loop and proceeds to the next iteration. For instance:

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

End Of Article

End Of Article