JavaScript Internals (521 Qs)•Part 3: DOM, Event Flow, Timers & Browser APIs (104 - 173)
What are the pros and cons of for loops
The for-loop is a commonly used iteration syntax in javascript. It has both pros and cons
Pros
- Works on every environment
- You can use break and continue flow control statements
Cons
- Too verbose
- Imperative
- You might face off-by-one errors.
Practical Code Example
javascript
// Standard for loop:
// Pro: Fastest raw performance, supports break and continue
// Con: Verbose syntax, manual counter tracking prone to off-by-one bugs
const items = [10, 20, 30, 40];
for (let i = 0; i < items.length; i++) {
if (items[i] === 30) break;
console.log(items[i]);
}
// for...of:
// Pro: Clean, iterable-friendly, supports break/continue
for (const item of items) {
console.log(item);
}