Javascript - loops repeat the piece code again and again till the condition is matched. Basically, loops automate the repetitive tasks within a program and it saves time & efficiency.
There are the followings javascript loops:
Javascript for loop starts with the for
keyword followed by a parenthesis and inside the parenthesis, Initialization, condition , and step values are inserted. For loop check the condition and if the condition is true then for loop continue the execution of Javascript code.
Source Code
for (i=1; i<=5; i++) {
document.write(i + "<br/>");
}
For loop is useful for iterating over an array. Let us take an example and understand it.
Source Code
var appDevelopment = ["flutter", "ionic", "swift"];
for(var i=0; i<appDevelopment.length; i++) {
document.write(appDevelopment[i]);
document.write("</br>");
}
The for..in the loop is used to access the array element and also access the element of the object.
Source Code
var fruits = {"mango": 50, "orange": 57, "grape":89 };
for(var fruit in fruits) {
document.write("<p>" + fruit + " = " + fruits[fruit] + "</p>");
}
The while
loop iterates the block of code until the condition is true. When while
loop condition fails then the loop is stopped.
Source Code
var i = 1;
while(i <= 5) {
document.write("<p>The number is " + i + "</p>");
i++;
}
The do..while
loop is a variant of the while
loop. With do..while
loop the block of code executes once and then check the condition. If the condition is true then the block of code will be executed again and again. If the condition fails then do....while loop stops the execution of the code.
Source Code
var i = 1;
do {
document.write("<p>The number is " + i + "</p>");
i++;
} while (i <= 5);