Loops Flashcards
for loop
The for loop allows you to execute a block of code a specific number of times.
for (let i = 0; i < 5; i++) {
console.log(i);
}
Output:
0
1
2
3
4
while loop
The while loop repeats a block of code as long as a specified condition is true.
let i = 0;
while (i < 5) {
console.log(i);
i++;
}
Output:
0
1
2
3
4
do-while loop
Similar to the while loop, the do-while loop also repeats a block of code as long as a specified condition is true. However, the code block is executed at least once before
let i = 0;
do {
console.log(i);
i++;
} while (i < 5);
Output:
0
1
2
3
4
for…in loop
The for…in loop iterates over the properties of an object.
const person = { name: “John”, age: 30, city: “New York” };
for (let key in person) {
console.log(key + “: “ + person[key]);
}
Output:
name: John
age: 30
city: New York
for…of loop
The for…of loop iterates over iterable objects such as arrays, strings, or other iterable collections.
const fruits = [“apple”, “banana”, “orange”];
for (let fruit of fruits) {
console.log(fruit);
}
Output:
apple
banana
orange