Loops are fundamental in programming, allowing you to execute a block of code multiple times. JavaScript provides several types of loops to handle different scenarios.
The for loop is used when the number of iterations is known. It consists of three parts: initialization, condition, and increment/decrement.
Syntax:
for (initialization; condition; increment) {
// code block to be executed
}Example:
for (let i = 0; i < 5; i++) {
console.log("Iteration:", i);
}This loop will print numbers from 0 to 4.(Codecademy)
The while loop executes a block of code as long as the specified condition evaluates to true. It's useful when the number of iterations is not known beforehand.(MDN Web Docs)
Syntax:
while (condition) {
// code block to be executed
}Example:
let i = 0;
while (i < 5) {
console.log("Iteration:", i);
i++;
}This loop will also print numbers from 0 to 4.
The do...while loop is similar to the while loop, but it guarantees that the code block is executed at least once before the condition is tested.
Syntax:
do {
// code block to be executed
} while (condition);Example:
let i = 0;
do {
console.log("Iteration:", i);
i++;
} while (i < 5);This loop will print numbers from 0 to 4.(Codecademy)
The for...in loop is used to iterate over the enumerable properties of an object.
Syntax:
for (let key in object) {
// code block to be executed
}Example:
const person = { name: "Alice", age: 25 };
for (let key in person) {
console.log(key + ": " + person[key]);
}This loop will print:
name: Alice
age: 25
The for...of loop is used to iterate over iterable objects like arrays, strings, maps, etc.
Syntax:
for (let value of iterable) {
// code block to be executed
}Example:
const numbers = [1, 2, 3];
for (let num of numbers) {
console.log(num);
}This loop will print:
1
2
3
forloop: Use when the number of iterations is known.whileloop: Use when the number of iterations is not known and depends on a condition.do...whileloop: Use when the loop must execute at least once.for...inloop: Use to iterate over object properties.for...ofloop: Use to iterate over iterable objects like arrays and strings.(GeeksforGeeks)
- Infinite Loops: Ensure that the loop's terminating condition will eventually be false.
- Off-by-One Errors: Be careful with loop boundaries to avoid missing iterations or overstepping array bounds.
- Using
for...inwith Arrays: Avoid usingfor...into iterate over arrays, as it iterates over all enumerable properties, not just array elements. Usefor,for...of, or array methods likeforEachinstead.
Answer: Both for and while loops are used for iteration. The for loop is generally used when the number of iterations is known, as it includes initialization, condition, and increment/decrement in one line. The while loop is preferred when the number of iterations is not known and depends on a condition evaluated before each iteration.
Answer: A do...while loop executes the code block once before checking the condition, ensuring that the block is executed at least once. In contrast, a while loop checks the condition before executing the code block, so the block may not execute at all if the condition is false initially.
Answer: The for...in loop is used to iterate over the enumerable properties (keys) of an object. The for...of loop is used to iterate over iterable objects like arrays, strings, maps, etc., accessing their values directly.
Answer: Using for...in with arrays can lead to unexpected behavior because it iterates over all enumerable properties, including those inherited through the prototype chain. This can result in iterating over properties that are not actual elements of the array. It's recommended to use for, for...of, or array methods like forEach for arrays.
Answer: To prevent infinite loops, ensure that the loop's terminating condition will eventually evaluate to false. This typically involves correctly updating variables involved in the condition within the loop body.
Answer: An off-by-one error occurs when a loop iterates one time too many or one time too few. This often happens due to incorrect loop boundaries, such as using < instead of <= in the loop condition.
Answer: Certainly!
const fruits = ["apple", "banana", "cherry"];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}This loop will print:
apple
banana
cherry
- JavaScript Loops - W3Schools
- Loops and iteration - MDN Web Docs
- JavaScript while and do...while Loop - Programiz
- 🌐 Website: CodeHarborHub
- 🐦 Twitter: @CodesWithAjay
- 💼 LinkedIn: Ajay Dhangar
© 2025 CodeHarborHub. All rights reserved.
Feel free to reach out if you have any questions or need further clarification on any of these topics!