Another type of loop is a for loop. For loops make it easy to act on a specific range of values.
For loops are similar to while loops, but they have two extra statements between the parentheses.
Look at this example of a while loop turned into a for loop:
let i = 0;
while (i < 10) {
console.log(i);
i++;
}
for (let i = 0; i < 10; i++) {
console.log(i);
}
Notice how the for loop is much cleaner? We can see all the code that deals with counting on a single line.
The three statements inside the parentheses run at specific times:
- The first statement runs before anything else in the for loop. It is often used to initialize variables for the loop.
- The second statement is identical to the while loop condition. The loop will run as long as this condition remains true.
- The third statement runs at the end of each loop. It is usually used for moving to the next item.
Use Cases
For loops are a great choice for working with strings, as they allow us to easily work through each index of the string:
let myString = 'The New York Times';
for (let i = 0; i < myString.length; i++) {
console.log(myString[i]);
}