JavaScript-Loops



This content originally appeared on DEV Community and was authored by Ranjani R

Looping is basically performing the same action a specified number of times or until a condition stays true. This helps us in reducing the number of lines of code that needs to be written in order to perform a repetitive task and thus reducing the complexity of the code. There are three main loops in JS.
1.While-Loop: In this the loop continues to execute until the given condition becomes false. Eg:

let i = 0;
while (i < 3) {
  console.log("While loop count:", i);
  i++;
}

Output:
While loop count: 0
While loop count: 1
While loop count: 2

2.Do…While-Loop: In this the loop will execute atleast once even if the condition is not met because the statement to be executed is written at the beginning of the loop while the condition is at the end. Eg:

let i = 3;
do {
  console.log("Do-while loop count:", i);
  i++;
} while (i < 3);

Output:
Do-while loop count: 3

In this even though the condition is false at the beginning itself, the loop is executed once.

3.For-Loop:In this type, the value initialization, condition checking and the increment is performed in one single line itself…this is the most commonly used loop type in programming. Eg:

for (let i = 0; i < 3; i++) {
  console.log("For loop count:", i);
}

Output:
For loop count: 0
For loop count: 1
For loop count: 2

In the above example, the browser first initializes i, checks condition i < 3, then increments i after each loop.

These are the looping statements present in JS. That’s all for today….see you all in the next post.


This content originally appeared on DEV Community and was authored by Ranjani R