Problem Statement
Explain the difference between for, while, and for of loops. When would you use each?
Explanation
JavaScript has multiple loop types suited for different scenarios.
The for loop is best when you know the number of iterations in advance or need an index counter. It has initialization, condition, and increment in one line. Use for loops for iterating with indices, counting, or when you need fine control over iteration.
The while loop is best when you do not know how many iterations are needed and want to continue until a condition becomes false. The condition is checked before each iteration. Use while loops for reading data until end, waiting for user input, or processing until a flag changes.
The for of loop introduced in ES6 iterates directly over values of iterables like arrays, strings, maps, or sets. It gives you the values, not indices. Use for of when you need values but not indices, for cleaner and more readable code. It works with break and continue.
For objects, use for in to iterate over properties, though Object keys or Object entries with for of is often cleaner.
Choose based on:
Whether you need indices. Whether iteration count is known. Whether you are working with arrays or objects.
Code Solution
SolutionRead Only
// for loop - when you need index or known iterations
const arr = ['a', 'b', 'c'];
for (let i = 0; i < arr.length; i++) {
console.log(i, arr[i]); // 0 'a', 1 'b', 2 'c'
}
// while loop - when iterations unknown
let data = getData();
while (data !== null) {
process(data);
data = getData(); // Keep going until null
}
// Practical while example
let attempts = 0;
let success = false;
while (!success && attempts < 3) {
success = tryOperation();
attempts++;
}
// for...of - when you need values, not indices
const fruits = ['apple', 'banana', 'cherry'];
for (const fruit of fruits) {
console.log(fruit); // Clean and simple
}
// for...of with strings
for (const char of 'hello') {
console.log(char); // h, e, l, l, o
}
// for...of with break
for (const num of [1, 2, 3, 4, 5]) {
if (num === 3) break;
console.log(num); // 1, 2
}
// for...in for objects (use carefully)
const person = { name: 'John', age: 30 };
for (const key in person) {
console.log(key, person[key]);
}
// Better way for objects
for (const [key, value] of Object.entries(person)) {
console.log(key, value);
}