Loops offer a quick and easy way to do something repeatedly.
You can think of a loop as a computerized version of the game where you tell someone to take X steps in one direction, then Y steps in another. For example, the idea "Go five steps to the east" could be expressed this way as a loop.
for (let step = 0; step < 5; step++) {
// Runs 5 times, with values of step 0 through 4.
console.log("Walking east one step");
}
There are many different kinds of loops, but they all essentially do the same thing: they repeat an action some number of times. (Note that it's possible that number could be zero!)
The various loop mechanisms offer different ways to determine the start and end points of the loop. There are various situations that are more easily served by one type of loop over the others.
The statements for loops provided in JavaScript are
A for loop repeats until a specified condition evaluates to false. The JavaScript for loop is similar to the Java and C for loop.
A for statement looks as follows
for (initialization; condition; afterthought)
statement
When a for loop executes, the following occurs
brands = ['Tata', 'Nike', 'Adidas', 'Apple', 'Microsoft']
for (let i = 0; i <= brands.length; i++) {
console.log(brands[i])
}
The do...while statement repeats until a specified condition evaluates to false.
A do...while statement looks as follows
do
statement
while (condition);
statement is always executed once before the condition is checked. (To execute multiple statements, use a block statement ({ }) to group those statements.)
If condition is true, the statement executes again. At the end of every execution, the condition is checked. When the condition is false, execution stops, and control passes to the statement following do...while.
let i = 0;
do {
i += 1;
console.log(i);
} while (i < 5);
A while statement executes its statements as long as a specified condition evaluates to true.
A while statement looks as follows
while (condition)
statement
If the condition becomes false, statement within the loop stops executing and control passes to the statement following the loop.