js Loop

Loops in JavaScript are used to execute a block of code repeatedly based on a condition. They make it possible to run a piece of code multiple times without having to write it multiple times. This is especially useful for working with arrays or performing repetitive tasks. There are four primary types of loops in JavaScript:

1. for loop

2. while loop

3. do-while loop

4. for-in loop

1. for Loop

The for loop is used to run a block of code a specified number of times. It is commonly used when the number of iterations is known beforehand.

Example:

<script>
 for (var i = 0; i < 5; i++) {
  console.log(i); <!-- Outputs: 0, 1, 2, 3, 4 -->
 }
</script>

2. while Loop

The while loop executes a block of code as long as the specified condition is true. It is used when the number of iterations is not known beforehand and depends on some condition being met.

Example:

<script>
 var i = 0;
 while (i < 5) {
  console.log(i); <!-- Outputs: 0, 1, 2, 3, 4 -->
  i++;
 }
</script>

3. do-while Loop

The do-while loop is similar to the while loop, but it guarantees that the block of code will be executed at least once because the condition is evaluated after the code execution.

Example:

<script>
 var i = 0;
 do {
  console.log(i); <!-- Outputs: 0, 1, 2, 3, 4 -->
  i++;
 } while (i < 5);
</script>

4. for-in Loop

The for-in loop is used to iterate over the enumerable properties of an object. It is useful for iterating through properties of an object or the elements of an array.

Example:

<script>
 var person = {fname: "John", lname: "Doe", age: 25};

 for (var key in person) {
  console.log(key + ": " + person[key]);
  <!-- Outputs: fname: John, lname: Doe, age: 25 -->
 }
</script>

4. for-in Loop

The for-in loop is used to iterate over the enumerable properties of an object. It is useful for iterating through properties of an object or the elements of an array.

Example:

<script>
 var person = {fname: "John", lname: "Doe", age: 25};

 for (var key in person) {
  console.log(key + ": " + person[key]);
  <!-- Outputs: fname: John, lname: Doe, age: 25 -->
 }
</script>