Tutorials / JavaScript Tutorials / For Loops

For Loops

tutorial javascript

Now you know the fundamentals of JavaScript. You’ve created variables and functions, and you’ve used if statements to conditionally take different actions in your code.

This tutorial introduces for loops, which let you repeat code multiple times.

For Loop Syntax

To create a for loop, first type the for keyword, and then in parentheses () provide three things:

  • Declare a variable to keep track of how many times you’ve looped, and initialize it to a number (usually 0): let index = 0;
  • Write a test that evaluates to a boolean value of false whenever the loop should stop: index < 10;
  • Reassign the variable so that it increases after each loop: index = index + 1; (which can be shortened to index++)

Then inside curly brackets {}, write the code that you want to repeat. Putting it all together, it looks like this:

Code Editor ?

See the Pen by Happy Coding (@KevinWorkman) on CodePen.

Repeating Code

The for loop syntax is new, so let’s talk about how to read it.

for (let index = 0; index < 10; index++) {
  document.write('<p>index: ' + index + '</p>');

Like all other code, the best way to read a for loop is line-by-line. The first line is doing a few things, so you might introduce some white space to make it easier to read:

for (
     let index = 0;
     index < 10;
  ) {
  document.write('<p>index: ' + index + '</p>');
  1. First, the for keyword tells you that the code is going to loop a certain number of times.
  2. Then the let index = 0; part tells you the loop index will start at zero.
  3. Then the index < 10 part tells you that the loop will continue until index reaches 10.
  4. Then the index++ part tells you that the loop variable increases by 1 each time the code loops.
  5. Finally, the document.write('<p>index: ' + index + '</p>'); line prints some content to the page

Now this is where for loops get interesting: when the code reaches the end of the loop, first it runs the index++ part, and then it starts back over at the top! Then it checks the index < 10 part, and if it’s still true, it runs the loop again. This process repeats until index < 10 evaluates to false, at which point the code skips to the bottom of the loop and keeps going.

Indexing and Incrementing

The above example starts the loop variable at 0. This is very common (and you’ll see why when you learn about arrays), but keep in mind that you can start your loop at any value you want.

Code Editor ?

See the Pen by Happy Coding (@KevinWorkman) on CodePen.

This code starts the loop at 7, and keeps looping until the loop variable exceeds 77. It also increases the loop variable by 7 after each iteration of the loop.


Comments and Questions

Happy Coding is a community of folks just like you learning about coding.
Do you have a comment or question? Post it here!