Minimizing Work Inside the Loop Body
What you'll learn: How to make your loops run faster by moving unchanging calculations outside the loop.
The Core Idea
Every time your loop runs, JavaScript executes all the code inside its body. If you're doing the same calculation or declaring the same variable over and over in each iteration, you're wasting time and resources.
Think of it like grocery shopping: if you need to check your shopping list 50 times while walking through the store, you're being inefficient. Better to read the list once before entering and remember what you need.
Hoisting Invariant Code
An invariant is something that doesn't change. If a calculation produces the same result every time through the loop, move it outside:
Before (inefficient):
for (let i = 0; i < 100; i++) {
let maxHeight = 500 * 2; // Calculated 100 times!
console.log(i * maxHeight);
}
After (optimized):
let maxHeight = 500 * 2; // Calculated once
for (let i = 0; i < 100; i++) {
console.log(i * maxHeight);
}
The same principle applies to array lengths:
// Instead of checking length each iteration
let items = ['a', 'b', 'c', 'd', 'e'];
let len = items.length; // Hoist this
for (let i = 0; i < len; i++) {
console.log(items[i]);
}
Why This Matters
With small loops, the difference is negligible. But with thousands or millions of iterations, these tiny savings add up dramatically. Your code runs faster and uses less memory.
Key Takeaway: Move any calculation, declaration, or operation that produces the same result on every iteration outside the loop body—compute once, use many times.