Apply JavaScript loops (for, while, do-while)

Resources | Subject Notes | Information Technology IT

JavaScript Loops

JavaScript Loops

Introduction

Loops are fundamental programming constructs that allow you to repeatedly execute a block of code. In JavaScript, there are three main types of loops: for, while, and do-while. Each loop type is suited for different scenarios.

1. for Loop

The for loop is used when you know in advance how many times you need to execute a block of code. It consists of three parts:

  • Initialization: Executed once at the beginning of the loop.
  • Condition: Evaluated before each iteration. The loop continues as long as the condition is true.
  • Increment/Decrement: Executed after each iteration.

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

Example:

Suggested diagram: A flowchart illustrating the structure of a for loop.

Iteration Initialization Condition Increment Code Execution
1 i = 0 i < 5 i = i + 1 console.log(i)
2 i = 0 i < 5 i = i + 1 console.log(i)
3 i = 0 i < 5 i = i + 1 console.log(i)
4 i = 0 i < 5 i = i + 1 console.log(i)
5 i = 0 i < 5 i = i + 1 console.log(i)

2. while Loop

The while loop repeatedly executes a block of code as long as a specified condition is true. The condition is checked at the beginning of each iteration.

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

Example:

Suggested diagram: A flowchart illustrating the structure of a while loop.

Iteration Condition Code Execution
1 count < 5 console.log(count)
2 count < 5 count = count + 1
3 count < 5 console.log(count)
4 count < 5 count = count + 1
5 count < 5 console.log(count)
6 count < 5 // Condition is now false, loop terminates

3. do-while Loop

The do-while loop is similar to the while loop, but it guarantees that the code block will be executed at least once, as the condition is checked at the end of the loop.

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

Example:

Suggested diagram: A flowchart illustrating the structure of a do-while loop.

Iteration Code Execution Condition
1 console.log(num) num < 5
2 num = num + 1 num < 5
3 console.log(num) num < 5
4 num = num + 1 num < 5
5 console.log(num) // Condition is now false, loop terminates

Choosing the Right Loop

The choice of which loop to use depends on the specific requirements of the task:

  • Use for when you know the number of iterations beforehand.
  • Use while when the number of iterations is not known and depends on a condition.
  • Use do-while when you need to execute the code block at least once, regardless of the initial condition.