DEV Community

Muhammad Rizwan Ashiq
Muhammad Rizwan Ashiq

Posted on

Loop

What is a loop?

A loop is a programming structure that repeats a sequence of instructions until a specific condition is met. Loops are used to execute a block of code multiple times. In this article, we will learn about different types of loops in JavaScript.

Algorithm

  1. Initialize a variable
  2. Check the condition
  3. Execute the code block
  4. Update the variable
  5. Repeat steps 2-4 until the condition is false
  6. Stop the loop
  7. Continue with the next statement
  8. End

Loop in JavaScript

In JavaScript, a loop is a control structure that allows you to execute a block of code repeatedly, based on a specified condition. Loops are useful when you want to perform the same operation multiple times, or when you want to process a large amount of data.

There are several types of loops in JavaScript:

  1. while loop
  2. do...while loop
  3. for loop
  4. for...in loop
  5. for...of loop

while Loop

The while loop is a control structure that allows you to execute a block of code as long as a specified condition is true.

Syntax

It has the following syntax:

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

The condition is evaluated before each iteration of the loop, and if it is true, the loop continues. If the condition is false, the loop ends.

Example

Here is an example of a while loop that counts from 1 to 10:

let i = 1;

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

In this example, the while loop continues to execute the code inside the loop as long as i is less than or equal to 5. After each iteration of the loop, i is incremented by 1. Output:

1
2
3
4
5
Enter fullscreen mode Exit fullscreen mode

do while Loop

The do-while loop is a control structure that allows you to execute a block of code at least once, and then repeat the code as long as a specified condition is true. Also known as exit-controlled loop.

Syntax

It has the following syntax:

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

The code inside the do block is executed first, and then the condition is evaluated. If the condition is true, the code inside the do block is executed again. If the condition is false, the loop ends.

Example

Here is an example of a do-while loop that counts from 1 to 5:

let i = 1;

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

In this example, the do-while loop executes the code inside the curly braces at least once, and then it continues to execute the code as long as the value of i is less than or equal to 5. After each iteration of the loop, i is incremented by 1.

You can use the do-while loop to perform an operation until a certain condition is met, like this:

let input = "";

do {
    input = prompt("Enter a command:");
    console.log(input);
} while (input !== "quit");
Enter fullscreen mode Exit fullscreen mode

In this example, the do-while loop continues to execute the code inside the loop as long as the value of input is not equal to quit.

For Loop

The for loop is a control structure that allows you to execute a block of code a specified number of times.

Syntax

It has the following syntax:

for (initialization; condition; increment) {
    // code to be executed
}
Enter fullscreen mode Exit fullscreen mode

The initialization expression is executed once at the beginning of the loop. The condition is evaluated before each iteration of the loop, and if it is true, the loop continues. If the condition is false, the loop ends. The increment expression is executed after each iteration of the loop.

Example

Here is an example of a for loop that counts from 1 to 10:

for (let i = 1; i <= 10; i++) {
    console.log(i);
}
Enter fullscreen mode Exit fullscreen mode

In this example, the for loop initializes the variable i to 1, and it continues to execute the code inside the loop as long as i is less than or equal to 10. After each iteration of the loop, i is incremented by 1.

You can use the for loop to perform a certain operation on each element of an array, like this:

const numbers = [1, 2, 3, 4, 5];

for (let i = 0; i < numbers.length; i++) {
    console.log(numbers[i]);
}
Enter fullscreen mode Exit fullscreen mode

In this example, the for loop iterates over the elements of the numbers array and prints each element to the console.

for in Loop

The for...in loop is a control structure that allows you to iterate over the properties of an object.

Syntax

It has the following syntax:

for (variable in object) {
    // code to be executed
}
Enter fullscreen mode Exit fullscreen mode

The variable is initialized with the name of each property of the object. The code inside the loop is executed once for each property of the object.

Example

Here is an example of a for...in loop that iterates over the properties of an object:

const person = {
    name: "John",
    age: 30,
    city: "New York",
};

for (let key in person) {
    console.log(key);
}
Enter fullscreen mode Exit fullscreen mode

In this example, the for...in loop iterates over the properties of the person object and prints the name of each property to the console. Like this:

name
age
city
Enter fullscreen mode Exit fullscreen mode

for of Loop

The for...of loop is a control structure that allows you to iterate over the elements of an iterable object.

Syntax

It has the following syntax:

for (variable of iterable) {
    // code to be executed
}
Enter fullscreen mode Exit fullscreen mode

The variable is initialized with the value of each element of the iterable object. The code inside the loop is executed once for each element of the iterable object.

Example

Here is an example of a for...of loop that iterates over the elements of an array:

```js title="Example"
const numbers = [1, 2, 3, 4, 5];

for (let number of numbers) {
console.log(number);
}




In this example, the `for...of` loop iterates over the elements of the numbers array and prints each element to the console like this:



```bash title="Output"
1
2
3
4
5
Enter fullscreen mode Exit fullscreen mode

break and continue

The break statement allows you to exit a loop or a switch statement.

The continue statement allows you to skip the current iteration of a loop.

Example

Here is an example of a for loop that uses the break statement to exit the loop when the value of i is equal to 5:

```js title="Example"
for (let i = 1; i <= 10; i++) {
if (i === 5) {
break;
}
console.log(i);
}




In this example, the for loop iterates over the numbers from 1 to 10, and it prints each number to the console. However, when the value of `i` is equal to 5, the break statement is executed, and the loop ends. Resulting in the following output:



```bash title="Output"
1
2
3
4
Enter fullscreen mode Exit fullscreen mode

Here is an example of a for loop that uses the continue statement to skip the current iteration when the value of i is equal to 5:

```js title="Example"
for (let i = 1; i <= 10; i++) {
if (i === 5) {
continue;
}
console.log(i);
}




In this example, the for loop iterates over the numbers from 1 to 10, and it prints each number to the console. However, when the value of `i` is equal to 5, the continue statement is executed, and the current iteration is skipped. Like this:



```bash title="Output"
1
2
3
4
6
7
8
9
10
Enter fullscreen mode Exit fullscreen mode

Nested Loops

You can use a loop inside another loop. This is called nesting.

Example

Here is an example of a nested for loop that prints the multiplication table of 2:

for (let i = 1; i <= 10; i++) {
    for (let j = 1; j <= 10; j++) {
        console.log(`${i} * ${j} = ${i * j}`);
    }
}
Enter fullscreen mode Exit fullscreen mode

In this example, the outer for loop iterates over the numbers from 1 to 10, and the inner for loop iterates over the numbers from 1 to 10 again. The code inside the inner loop is executed 100 times, and it prints the multiplication table of 2 to the console.

While vs. Do-While vs. For

The while loop, the do-while loop, and the for loop are all used to execute a block of code multiple times. However, they have some differences.

While Loop Do-While Loop For Loop
The condition is evaluated before each iteration of the loop. The condition is evaluated after each iteration of the loop. The condition is evaluated before each iteration of the loop.
The code inside the loop is executed zero or more times. The code inside the loop is executed at least once. The code inside the loop is executed zero or more times.
The initialization expression is executed once at the beginning of the loop. The initialization expression is executed once at the beginning of the loop. The initialization expression is executed once at the beginning of the loop.
The increment expression is executed after each iteration of the loop. The increment expression is executed after each iteration of the loop. The increment expression is executed after each iteration of the loop.

Summary

In this lesson, you learned about the different types of loops in JavaScript:

  • The while loop
  • The do-while loop
  • The for loop
  • The for...in loop
  • The for...of loop

Top comments (0)