for (expression 1; expression 2; expression 3) {
// code block to be executed }
for (let i = 0; i < 5; i++) {
text += "The number is " + i + "<br>";
}
Loops can execute a block of code a number of times. For loops use three expressions. A starting point, conditional, and an iteration.
const array1 = [6, 19, 20];
const array2 = [19, 81, 2];
for (let i = 0; i < array1.length; i++) {
for (let j = 0; j < array2.length; j++) {
if (array1[i] === array2[j]) {
console.log('Both arrays have the number: ' + array2[j]);
}
}
}
For each round of the outer for loop, the inner for loop will run completely.
let i = 0;
while (i < 6) {
if (i === 3) {
break;
}
i = i + 1;
}
console.log(i); // Expected output: 3
Breaks out of a loop if executed.
const object = { a: 1, b: 2, c: 3 };
for (const property in object) {
console.log(`${property}: ${object[property]}`);
}
// Expected output:
// "a: 1"
// "b: 2"
// "c: 3"
The javascript for in statement loops through the properties of objects and arrays.
let n = 0;
while (n < 3) {
n++;
}
console.log(n);
// Expected output: 3
Runs while a condition is true.
let text = '';
for (let i = 0; i < 10; i++) {
if (i === 3) {
continue;
}
text = text + i;
}
console.log(text); // Expected output: "012456789"
"Jumps over" one iteration in a loop and continues.
const array1 = ['a', 'b', 'c'];
for (const element of array1) {
console.log(element);
}
// Expected output: "a"
// Expected output: "b"
// Expected output: "c"
Loops through the values of an iterable object, Arrays, Strings, Maps, NodeLists, and more.
let result = '';
let i = 0;
do {
i = i + 1;
result = result + i;
} while (i < 5);
console.log(result);
// Expected output: "12345"
Creates a loop that executes until a condition evaluates to false.