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.
To create a for
loop, first type the for
keyword, and then in parentheses ()
provide three things:
let index = 0;
false
whenever the loop should stop: index < 10;
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:
See the Pen by Happy Coding (@KevinWorkman) on CodePen.
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;
index++
) {
document.write('<p>index: ' + index + '</p>');
}
for
keyword tells you that the code is going to loop a certain number of times.let index = 0;
part tells you the loop index will start at zero.index < 10
part tells you that the loop will continue until index reaches 10.index++
part tells you that the loop variable increases by 1
each time the code loops.document.write('<p>index: ' + index + '</p>');
line prints some content to the pageNow 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.
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.
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.
Use JavaScript for loops to repeat code multiple times.
Happy Coding is a community of folks just like you learning about coding.
Do you have a comment or question? Post it here!
Comments are powered by the Happy Coding forum. This page has a corresponding forum post, and replies to that post show up as comments here. Click the button above to go to the forum to post a comment!