Essential JavaScript
Introduction
JavaScript Basics
Numbers
Strings
Logic
Variables
Loops
Objects
Arrays
Going Further
Essential JavaScript
Introduction
JavaScript Basics
Numbers
Strings
Logic
Variables
Loops
Objects
Arrays
Going Further
For Loop
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]); }
Learning Goals
I know what a for loop is
I understand how a for loop can make code cleaner
I can convert a while loop into a for loop
I understand how the three statements in the for loop parentheses work
Code Editor
Click "Run Code" to execute your JavaScript in a secure sandbox and see the output below.
Console Output
0 output lines