Multiple Variables in For Loops
You'll learn how to manage more than one counter or variable within a single for loop declaration.
Why Use Multiple Variables?
Sometimes you need to track two things at once in a loop. For example, you might want to count forward with one variable while counting backward with another, or track both an index and a step size simultaneously. JavaScript's for loop lets you declare and update multiple variables in the same statement, keeping related logic together.
The Syntax
You separate multiple variables with commas in both the initialization and the final-expression sections:
for (let i = 0, j = 10; i < 5; i++, j--) {
console.log("i:", i, "j:", j);
}
// i: 0 j: 10
// i: 1 j: 9
// i: 2 j: 8
// i: 3 j: 7
// i: 4 j: 6
Notice the commas: let i = 0, j = 10 declares two variables, and i++, j-- updates both on each iteration.
How It Works
- Initialization:
let i = 0, j = 10runs once before the loop starts - Condition:
i < 5is checked before each iteration (only one condition allowed) - Final-expression:
i++, j--both execute after each loop body, before the next condition check
When Is This Useful?
This pattern shines when you need synchronized counters—like comparing elements from opposite ends of a range, or tracking progress in two related sequences at once.
Key Takeaway: You can declare and update multiple variables in a for loop by separating them with commas in the initialization and final-expression sections, keeping related counters synchronized and your code concise.