A loop repeats a set of instructions until a specified condition, called a stopping condition, is reached.
A for loop contains three expressions separated by a semi-colon inside the parentheses:
For example
for (let i = 0; i < 3; i++) {
console.log(i);
}
// Output:
0;
1;
2;
In the code block above:
let i = 0
, so the loop will start counting at 0.i < 3
, so the loop will run as long as i is less than 4.i++
. After each loop, the count value will increase by 1. For the first iteration, the counter will equal 0. For the second iteration, the counter will equal 1, and so on.console.log(i)
will execute until the condition evaluates to false.Loop through an array
To loop through each element in an array, we use the array.length
property in its condition.
For example
const vacationSpots = ["London", "Copenhagen", "Saigon"];
for (let i = 0; i < vacationSpots.length; i++) {
console.log(`I would love to visit ${vacationSpots[i]}`);
}
The while
loop loops through a block of code as long as a specified condition is true.
while (condition) {
// code block
}
For example
while (i < 5) {
text += "The number is " + i;
i++;
}
do...while
loops run code at least once and only check the stopping condition after the first execution.
do {
// code block to be executed
} while (condition);
switch (expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
The continue
keyword skips the current iteration.
let result = [];
for (let i = 0; i < 10; i++) {
if (i % 2 === 0) {
continue;
}
result.push(i);
}
console.log(result);
// Result: [ 1, 3, 5, 7, 9 ]
The break
keyword allows programs to leave a loop during the execution of their block.
let result = [];
for (let i = 0; i < 10; i++) {
if (i % 3 === 0) {
break;
}
result.push(i);
}
console.log(result);
// Result: [ 1, 2 ]