For Loops
A for loop repeats a block of code while a condition holds, with a counter that changes on each pass. It is the loop to use when you need the index itself, want to step by something other than one, or want to run backwards. For simply visiting every item of an array, for...of is shorter.
The three parts
Section titled “The three parts”The brackets after for hold three parts, separated by semicolons:
- The initialiser runs once, before the loop starts, and usually declares the counter.
- The condition is checked before each pass, and the loop ends as soon as it is false.
- The update runs after each pass, and usually moves the counter on.
const chores = ['dishes', 'laundry', 'hoovering'];
for (let i = 0; i < chores.length; i++) { console.log(`${i + 1}. ${chores[i]}`);}This prints:
1. dishes2. laundry3. hooveringThe condition uses < rather than <=, because the last index is length - 1. Using <= runs one pass too many and reads undefined.
Counting down and stepping
Section titled “Counting down and stepping”The counter can start anywhere and change by any amount:
for (let n = 10; n > 0; n -= 3) { console.log(n);}This prints:
10741Counting down is useful when removing items from an array inside the loop. Removing an item moves every later item down one index, so a forward loop skips the item after each one it removes:
const basket = ['milk', 'expired yoghurt', 'expired ham', 'bread'];
for (let i = 0; i < basket.length; i++) { if (basket[i].startsWith('expired')) { basket.splice(i, 1); }}console.log(basket);This prints:
[ 'milk', 'expired ham', 'bread' ]Running the same loop from the end avoids the problem, because the items that move have already been checked:
const basket = ['milk', 'expired yoghurt', 'expired ham', 'bread'];
for (let i = basket.length - 1; i >= 0; i--) { if (basket[i].startsWith('expired')) { basket.splice(i, 1); }}console.log(basket);This prints:
[ 'milk', 'bread' ]Where a new array is acceptable, filter() is simpler still.
break and continue
Section titled “break and continue”continue skips the rest of the current pass and moves on to the next one. break ends the loop altogether:
const temps = [14, 18, -2, 21, 99, 16];
for (let i = 0; i < temps.length; i++) { if (temps[i] < 0) { console.log(`skipping reading ${i}`); continue; } if (temps[i] > 50) { console.log(`bad reading at ${i}, stopping`); break; } console.log(temps[i]);}This prints:
1418skipping reading 221bad reading at 4, stoppingMore than one variable
Section titled “More than one variable”The initialiser and the update can each hold several expressions, separated by commas. This checks whether a word reads the same backwards by moving two counters towards each other:
const word = 'level';
let isPalindrome = true;for (let left = 0, right = word.length - 1; left < right; left++, right--) { if (word[left] !== word[right]) { isPalindrome = false; break; }}console.log(isPalindrome);This prints:
truelet or var for the counter
Section titled “let or var for the counter”Declare the counter with let. A let counter exists only inside the loop, whereas a var counter belongs to the surrounding function or script and is still there afterwards:
for (let i = 0; i < 3; i++) { // i exists only inside the loop}console.log(typeof i);
for (var j = 0; j < 3; j++) {}console.log(j);This prints:
undefined3let also gives each pass its own copy of the counter, which matters when a function created in the loop runs later. Closures with Loops shows the difference.
Steve Griffith covers this topic in his video JavaScript for loops.