Loop:
Loops in JavaScript are used to reduce repetitive tasks by repeatedly executing a block of code as long as a specified condition is true.
1. for Loop
The for loop repeats a block of code a specific number of times. It contains initialization, condition, and increment/decrement in one line.
for (let i = 1; i <= 3; i++) {
console.log("Count:", i);
}
for in loop:
The for-in loop iterates over the enumerable keys of an object.
const person = { name: "Alice", age: 22, city: "Delhi" };
for (let key in person) {
console.log(key, ":", person[key]);
}
while:
The while loop executes as long as the condition is true. It can be thought of as a repeating if statement.
let i = 0;
while (i < 3) {
console.log("Number:", i);
i++;
}
when the condition is false, the code of the block is not executed.
Do While:
The do...while statement repeats until a specified condition evaluates to false.
do
statement
while (condition);
for...in statement:
The for...in statement iterates a specified variable over all the enumerable properties of an object. For each distinct property, JavaScript executes the specified statements.
While for...in iterates over property names, for...of iterates over property values:
const arr = [3, 5, 7];
arr.foo = "hello";
for (const i in arr) {
console.log(i);
}
// "0" "1" "2" "foo"
for (const i of arr) {
console.log(i);
}
// Logs: 3 5 7
Top comments (0)