In JavaScript, loops are used to conduct repetitive activities based on a condition.
In JavaScript, there are four different forms of loops.
For loops are typically used to repeat code for a certain number of times.
for (initialization; condition; finalExpression) {
// code block
}
for (i=1; i<=5; i++) {
document.write(i + "<br/>")
}
1
2
3
4
5
The while loop iterates across a block of code as long as a condition is met.
while (condition)
{
// code block
}
let i = 1;
while (i <= 5) {
document.write(i + "<br/>")
i++;
}
1
2
3
4
5
Whether the condition is true or not, the do while loop script is executed at least once.
do{
// code block
} while (condition);
var i=1;
do{
document.write(i + "<br/>");
i++;
}while (i<=5);
1
2
3
4
5
The JavaScript for in statement iterates across an Objects properties.
for (key in object) {
// code block
}
const employee = {emiId:"101", empTitle:"Developer", age:36};
let result = "";
for (let val in employee) {
result += employee[val] + " ";
}
101 Developer 36