Resources | Subject Notes | Information Technology IT
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.
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:
Syntax: for (initialization; condition; increment/decrement) { // code to be executed }
Example:
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) |
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:
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 |
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:
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 |
The choice of which loop to use depends on the specific requirements of the task:
for
when you know the number of iterations beforehand.while
when the number of iterations is not known and depends on a condition.do-while
when you need to execute the code block at least once, regardless of the initial condition.