For
for (let i=0; i < 10; i++) {
console.log('Loop ' + i);
}
// or in one line
for (let i=0; i < 10; i++) console.log('Loop ' + i);
For without arguments
let i = 0; // we have i already declared and assigned
for (; i < 3; i++) { // no need for "begin"
alert( i ); // 0, 1, 2
}
// same as while (i < 3)
let i = 0;
for (; i < 3;) {
alert( i++ );
}
Continue & break
for (let i=0; i < 10; i++) {
if (i == 3) continue; // skip
if (i == 9) break; // end loop
console.log('Loop ' + i);
}
While
let i = 0;
while (i < 3) {
i++; // 0, 1, 2
console.log(i);
}
Do
let i = 0;
do {
i++;
console.log(i);
} while (i < 10)
Labels for break/continue
// break out from nested loops
outer:
for (let i = 0; i < 10; i++) {
for (let j = 0; j < 10; j++) {
if (j == 5) break outer;
console.log(i, j);
}
}
console.log('done');
for...in Iterates over all enumerable properties of an object that are keyed by strings (ignoring ones keyed by Symbols)
let obj = { name: "John", age: 30, isAdmin: true };
// iterates over properties of an object
for (let key in obj) {
console.log( key, obj[key] ); // name John, age 30, isAdmin true
}
for...of Iterates over iterable objects
const arr = ['a', 'b', 'c'];
for (const element of arr) {
console.log(element); // a b c
}
forEach Executes a provided function once for each array element
const arr = ['a', 'b', 'c'];
arr.forEach(element => console.log(element)); // a b c