Loops in JavaScript (for, while, do while, forEach)
for
The for
loop is the most basic loop in JavaScript. It looks like this:
for (initialization; condition; increment) {
// Statements go here
}
The initialization
statement is executed once, before the loop starts. It is typically used to initialize a counter variable.
The condition
is evaluated on each iteration of the loop. If it evaluates to true, the loop continues. If it evaluates to false, the loop stops.
The increment
statement is executed after each iteration of the loop. It is typically used to update the counter variable.
Here is an example of a for
loop:
while
The while
loop is used to execute a statement or a block of statements repeatedly until a condition evaluates to false. It looks like this:
while (condition) {
// Statements go here
}
The condition is evaluated before each iteration of the loop. If it evaluates to true, the loop continues. If it evaluates to false, the loop stops.
Here is an example of a while
loop:
do while
The do while
loop is similar to the while loop, but the condition is evaluated after each iteration of the loop. It looks like this:
do {
// Statements go here
} while (condition);
The statements inside the do while loop will be executed at least once, even if the condition evaluates to false.
Here is an example of a do while
loop:
forEach
The forEach
loop is used to iterate over arrays. It looks like this:
array.forEach(function(element, index, array) {
// Statements go here
});
The function inside the forEach loop will be executed once for each element in the array. The element, index, and array arguments are passed to the function automatically.
Here is an example of a forEach
loop: