Explain different types of loops in JavaScript?

The JavaScript loops are used to iterate the piece of code using for, while, do-while, or for-in loops. It makes the code compact. It is mostly used in arrays.

There are four types of loops in JavaScript.

for loop
while loop
do-while loop
for-in loop

JavaScript For loop - The JavaScript for loop iterates the elements for a fixed number of times. It should be used if a number of iterations is known. The syntax of for loop is given below.


for (initialization; condition; increment) 

{ 

    code to be executed 

}

JavaScript while loop - The JavaScript while loop iterates the elements for the infinite number of times. It should be used if number of iteration is not known. The syntax of while loop is given below.

while (condition) 

{ 

    code to be executed 

}

JavaScript do while loop - The JavaScript do while loop iterates the elements for the infinite number of times like while loop. But, code is executed at least once whether the condition is true or false. The syntax of do while loop is given below.

do{ 

 code to be executed 

}while (condition);

Javascript For in loop - The for…in loop in JavaScript allows you to iterate over all property keys of an object.

for (key in object) {
    // body of for...in
}