Loops
When you need to execute the same block of code multiple times, you use a loop. A traditional for loop in JavaScript follows the standard C-style syntax.
The For Loop Syntax
for (let i = 0; i < 5; i++) {
console.log(i);
}
// Output: 0, 1, 2, 3, 4
A for loop is composed of three distinct statements separated by semicolons:
- Initialization (
let i = 0): Executed exactly once before the loop begins. It is typically used to create a counter variable. - Condition (
i < 5): Evaluated before every loop iteration. If it evaluates totrue, the loop body executes. If it evaluates tofalse, the loop immediately terminates. - Increment (
i++): Executed at the very end of every loop iteration, right before the condition is evaluated again.
Practical Example
Loops are essential for tasks involving accumulators, such as calculating the total cost of a batch of items where the price scales dynamically.
function bulkCost(numItems) {
let totalCost = 0;
// Start at 0, run exactly numItems times
for (let i = 0; i < numItems; i++) {
// Base fee is 1.0, increases by 0.01 per subsequent item
const itemCost = 1.0 + (i * 0.01);
totalCost += itemCost;
}
return totalCost;
}
console.log(bulkCost(4)); // Output: 4.06