The **for** loop has three parts: **initialization** (runs once before the loop), **condition** (checked before each iteration), and **update** (runs after each iteration). If condition is false initially, the body never runs. All three parts are optional.
1Understanding for Loop
The for loop has three parts: initialization (runs once before the loop), condition (checked before each iteration), and update (runs after each iteration). If condition is false initially, the body never runs. All three parts are optional.
Cache array.length in a variable when iterating large arrays to avoid recalculating it each iteration.
// Sum of numbers 1-100
let sum = 0;
for (let i = 1; i <= 100; i++) {
sum += i;
}
console.log(sum); // 5050 (Gauss formula)
// Iterate backwards
const arr = ['a', 'b', 'c'];
for (let i = arr.length - 1; i >= 0; i--) {
console.log(arr[i]);
}2Practical Example
Here is a real-world application of for Loop showing how it is used in production JavaScript code.
// Nested loops: multiplication table
for (let i = 1; i <= 3; i++) {
for (let j = 1; j <= 3; j++) {
process.stdout.write((i * j) + '\t');
}
console.log();
}3Best Practices
Follow these guidelines when working with for Loop:
1. Use let for loop counter to keep it block-scoped
2. Prefer for...of when you don't need the index
3. Break early with break when the target is found
Tip: Cache array.length in a variable when iterating large arrays to avoid recalculating it each iteration.
// Sum of numbers 1-100
let sum = 0;
for (let i = 1; i <= 100; i++) {
sum += i;
}
console.log(sum); // 5050 (Gauss formula)
// Iterate backwards
const arr = ['a', 'b', 'c'];
for (let i = arr.length - 1; i >= 0; i--) {
console.log(arr[i]);
}