Bytes

Iterating with Loops in JavaScript: for, while, and do-while Loops

Introduction

In programming, looping is a control structure that repeats a set of instructions multiple times until a specific condition is met. This allows us to execute the same block of code multiple times without having to write it out every time. Loops are essential for automating repetitive tasks and creating more efficient and concise code. Looping is important in programming because it allows us to perform the same actions repeatedly without having to manually repeat the code. This not only saves time but also ensures accuracy and consistency in our code. Additionally, loops enable us to process large sets of data and perform complex operations on them.

JavaScript supports various types of loops, including for loops, while loops, and do-while loops. In JavaScript, loops are used to iterate over arrays, manipulate the DOM, and perform other operations that involve repetitive tasks.

For Loop

Syntax of for loop The for loop is the most commonly used loop in JavaScript. Its syntax is as follows:

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

The initialization statement is executed before the loop starts and is used to initialize the loop variable. The condition statement is evaluated before each iteration of the loop, and if it is true, the loop continues. The increment/decrement statement is executed after each iteration of the loop and is used to update the loop variable. This process is repeated until the condition becomes false. If the condition is false initially, the loop will not be executed at all.

Examples of for loop Let's take a look at some examples of for loops in JavaScript:

Example 1: Printing numbers from 1 to 5

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

Output:

1
2
3
4
5

Example 2: Summing numbers from 1 to 10

let sum = 0;
for (let i = 1; i <= 10; i++) {
  sum += i;
}
console.log(sum);

Output:

55

Nested for loop

A nested for loop is a loop inside another loop. It is used to iterate over multi-dimensional arrays and perform other complex operations. The syntax of a nested for loop is as follows:

for (let i = 0; i < array1.length; i++) {
  for (let j = 0; j < array2.length; j++) {
    // code to be executed
  }
}

The outer loop iterates over the first array, and the inner loop iterates over the second array. The code inside the inner loop is executed for each combination of elements from the two arrays.

While Loop

Syntax of while loop The while loop is a basic looping structure in JavaScript that executes a block of code as long as a specified condition is true. The syntax for a while loop is as follows:

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

When a while loop is executed, the condition is evaluated before the code block is executed. If the condition is true, the code block is executed. After the code block is executed, the condition is evaluated again. This process continues until the condition becomes false.

Examples of while loop Let's take a look at a few examples of how the while loop can be used in JavaScript:

Example 1: Counting from 1 to 5 using a while loop

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

Output:

1
2
3
4
5

Example 2: Displaying elements of an array using a while loop

const fruits = ['apple', 'banana', 'orange', 'mango'];
let i = 0;
while (i < fruits.length) {
  console.log(fruits[i]);
  i++;
}

Output:

apple
banana
orange
mango

Nested while loop

A while loop can also be nested inside another while loop. This is useful when you need to perform a task multiple times, and each iteration of the outer loop requires multiple iterations of the inner loop. Here's an example:

let i = 1;
while (i <= 3) {
  let j = 1;
  while (j <= 3) {
    console.log(i + " " + j);
    j++;
  }
  i++;
}

Output:

1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3

Do-While Loop

Syntax of do-while loop The do-while loop is similar to the while loop, except that the code block is executed at least once, regardless of whether the condition is true or false. The syntax for a do-while loop is as follows:

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

The code block is executed once, and then the condition is evaluated. If the condition is true, the code block is executed again, and the process continues until the condition becomes false.

Examples of do-while loop Let's take a look at a few examples of how the do-while loop can be used in JavaScript:

Example 1: Displaying numbers from 1 to 5 using a do-while loop

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

Output:

1
2
3
4
5

Example 2: Asking for user input using a do-while loop

let input;
do {
input = prompt("Enter a number between 1 and 10:");
} while (input < 1 || input > 10);
console.log("You entered: " + input);

Differences between while loop and do-while loop

The primary difference between the while loop and do-while loop is that the while loop evaluates the condition before the code block is executed, while the do-while loop evaluates the condition after the code block is executed. This means that the do-while loop will always execute the code block at least once, while the while loop may not execute the code block at all if the condition is false.

Loop Control Statements

A. break statement The break statement is used to terminate a loop before it has completed all of its iterations. When a break statement is encountered inside a loop, the loop is immediately terminated, and the program continues to execute the next statement after the loop. Here's an example:

let i = 1;
while (i <= 5) {
  if (i === 3) {
    break;
  }
  console.log(i);
  i++;
}

Output:

1
2

In this example, the while loop is terminated when the value of i is equal to 3, and the program continues to execute the next statement after the loop.

B. continue statement The continue statement is used to skip the current iteration of a loop and move on to the next iteration. When a continue statement is encountered inside a loop, the program immediately moves on to the next iteration, skipping any remaining statements in the current iteration. Here's an example:

for (let i = 1; i <= 5; i++) {
  if (i === 3) {
    continue;
  }
  console.log(i);
}

Output:

1
2
4
5

In this example, the for loop skips the third iteration when the value of i is equal to 3, and the program immediately moves on to the next iteration.

Conclusion

Looping is an essential concept in programming and is used extensively in JavaScript. JavaScript provides developers with various looping structures and loop control statements that enable them to execute a block of code repeatedly and control the flow of the program. Understanding these looping structures and control statements is essential for any JavaScript developer.

Module 4: JavaScript Control Flow OperationsIterating with Loops in JavaScript: for, while, and do-while Loops

Top Tutorials

Related Articles

AlmaBetter
Made with heartin Bengaluru, India
  • Official Address
  • 4th floor, 133/2, Janardhan Towers, Residency Road, Bengaluru, Karnataka, 560025
  • Communication Address
  • 4th floor, 315 Work Avenue, Siddhivinayak Tower, 152, 1st Cross Rd., 1st Block, Koramangala, Bengaluru, Karnataka, 560034
  • Follow Us
  • facebookinstagramlinkedintwitteryoutubetelegram

© 2024 AlmaBetter