Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

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:

for (var i = 0; i < 10; i++) {
  console.log(i);
}
This loop will print the numbers 0 through 9 to the console.

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:

var i = 0;

while (i < 10) {
  console.log(i);
  i++;
}
This loop will print the numbers 0 through 9 to the console.

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:

var i = 0;

do {
  console.log(i);
  i++;
} while (i < 10);
This loop will print the numbers 0 through 9 to the console.

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:

var numbers = [0,1,2,3,4,5,6,7,8,9]

numbers.forEach(function(element, index, array) {
  console.log(element);
});
This loop will print the numbers 0 through 9 to the console.