#atom
ID: JS-007
Date: [Insert Date]
Content:
Loops allow you to execute a block of code repeatedly. JavaScript provides several types of loops for different use cases.
for
Loop:
- Iterates a block of code a specific number of times.
Syntax:
for (initialization; condition; increment) {
// Code to execute
}
Example:
for (let i = 0; i < 5; i++) {
console.log(i); // 0, 1, 2, 3, 4
}
while
Loop:
- Executes a block of code as long as a condition is
true
.
Syntax:
while (condition) {
// Code to execute
}
Example:
let i = 0;
while (i < 5) {
console.log(i); // 0, 1, 2, 3, 4
i++;
}
do...while
Loop:
- Similar to
while
, but the block of code is executed at least once, even if the condition isfalse
.
Syntax:
do {
// Code to execute
} while (condition);
Example:
let i = 0;
do {
console.log(i); // 0
i++;
} while (i < 0);
for...in
Loop:
- Iterates over the enumerable properties of an object.
Syntax:
for (let key in object) {
// Code to execute
}
Example:
const person = { name: 'Alice', age: 25 };
for (let key in person) {
console.log(`${key}: ${person[key]}`);
}
// Output:
// name: Alice
// age: 25
for...of
Loop:
- Iterates over iterable objects (e.g., arrays, strings).
Syntax:
for (let value of iterable) {
// Code to execute
}
Example:
const colors = ['red', 'green', 'blue'];
for (let color of colors) {
console.log(color); // red, green, blue
}
Connections:
Connections:
Sources: