
Loops in JavaScript are used to perform repeated tasks based on a condition. Conditions typically return true or false when analysed. A loop will continue running until the defined condition returns false, The JavaScript loops are used to iterate the piece of code using for, while, do-while. It makes the code compact. It is mostly used in an array.
For Loop
The for loop statement in JavaScript allows you to create a loop with three optional expressions. The for loop is the simplest type of loop. It consists of the three key components listed below:
Syntax
for(initialization; condition; iteration statement){
// statements
}// example of a for loop
const cars = ["BMW", "Volvo", "Saab", "Ford", "Fiat", "Audi"]
let text = ""
for(let i = 0; i < cars.length; i++){
text += cars[i] + "<br>";
}
first The startup of the loop, when we set our cars to a beginning value. Before the loop starts, the initialization statement is executed.
secondly, The test statement determines whether or not a particular condition is true. If the condition is true, the code inside the loop will be performed; if it is false, the control will exit the loop.
The iteration statement is the last element when you can increase or decrease.
WHILE LOOP
The while loop statement generates a loop that runs a specified statement as long as the test condition is true. Before executing the statement, the condition is checked.
While loop Syntax
while(condition){
// code block to be executed
};// example of a while loop
let output = "";
let i = 0;
while(i < 10){
output += "The number is" + i;
i++;
}
The code in the loop in the following example will be executed repeatedly as long as a variable I is less than 10, note that the loop will never end if you fail to increment the variable used in the condition. This will cause your browser to freeze.
DO WHILE
The do-while loop is similar to the while loop in that it checks the condition only after it has completed its instructions, and it always runs at least once.
Syntax
do{
// code block to be executed
} while(condition);// example of a do while loop
let result = "";
let i = 0;
do {
i = i + 1;
result = result + i;
} while (i < 5);
console.log(result);
The main difference between a while and a do-while loop is the location where the condition is checked. The while loop checks the condition before running any of the while loop’s statements, whereas the do-while loop tests the condition after the loop’s statements have been performed.