FOR, DO-WHILE LOOP IN JAVASCRIPT | PART-2

Share the post
Hello All, Today we will discuss the major loop for a loop. The most common loop is for a loop. After that, We will look into a while & do-while loop. We will see all loops with an example as we discussed earlier.

for loop :

Syntax :
       

for (condition 1,condition 2, condition 3){
    //CODE
}
condition 1: This condition will execute before the code execution.
condition 2: This is the condition.
condition 3: This condition will execute after the code execution.
Example :
We will see the same example as we have seen in part- 1.

var array = [“A”, “B”, “C”, “D”, “E”];
for(let x = 0; x < array.length ; x++){
console.log(array[x]);
}

Output :
output

As you can see in the above example, first we initialize the value for x = 0 & remember that always define the value of a variable using let & not by var. As if you defined it using var then that variable available outside the scope of for loop also, then we will write the condition for loop to iterate only as per array length & finally increase the value of x by 1.

while loop :

while the loop is running till the condition defined is true. let’s see the syntax below :
Syntax :
while(condition){
    //CODE
}
Example :

var array = [“A”, “B”, “C”, “D”, “E”];
let k = 0;
while (k < array.length){
    console.log(array[k]);
    k++;
}
Output :
output
  In the above example, we took the condition that executes the code inside while loop until array length is greater than. Now, we will see the do-while loop.

do-while loop :

It will execute the code inside the do without considering the while condition & it will repeat the code.
Please see the below syntax for the do-while loop.
Syntax :
do{
    //CODE
}
while (condition)
Example :
var array = [“A”, “B”, “C”, “D”, “E”];
let k = 0;
do{
console.log(array[k]);
k++;}
while (k < array.length);

Output :

output

In this example, We have seen that code is executed inside do. It doesn’t depend on the condition in the while loop.

Leave a Comment