Caching Array Length in For Loops
You'll learn when and why storing an array's length in a variable can make tight loops run faster.
Every time you write i < arr.length in a for loop's condition, JavaScript must access the array's length property. In a loop that runs thousands or millions of times, those repeated property lookups add up—like checking the price tag every single time you grab an item from your shopping cart instead of remembering the total once.
Caching means storing that value once before the loop starts:
const numbers = [1, 2, 3, 4, 5];
// Without caching: checks .length every iteration
for (let i = 0; i < numbers.length; i++) {
console.log(numbers[i]);
}
// With caching: checks cached value every iteration
const len = numbers.length;
for (let i = 0; i < len; i++) {
console.log(numbers[i]);
}
Both loops work identically, but the second avoids repeated property access.
When Does This Matter?
In tight loops with many iterations (thousands+), the savings can be measurable. For small arrays (< 100 elements), the difference is negligible and modern JavaScript engines often optimize it away automatically.
Modern Considerations
Today's engines are smart—they often cache array.length internally for simple loops. However, if your loop modifies the array's length or performs complex operations, caching guarantees you're not recalculating anything.
For most everyday code, readability matters more than micro-optimizations. Use caching when you're working with large datasets or performance-critical sections.
Key Takeaway: Caching an array's length before a loop prevents repeated property lookups, offering a small performance boost in tight, high-iteration loops—though modern engines often optimize this automatically.