Learn the basics of for loops in JavaScript.
Loops are one of the fundamental constructs that enable us to control the flow of our program. A for loop is a type of loop that repeats a block of code a specific number of times.
A for
loop in JavaScript follows this structure:
Go through the following slides to see how for
loops work.
A few key things to note:
for
loops typically start with0
instead of1
.- You can use the variable
i
in the code to be executed during the loop.- The
for
loop increments the variable at the end of each loop.- Once the condition is false, we exit the
for
loop.- You can include as many lines of code as you want inside of the
for
loop.- While the variable
i
is typically used, you can use any variable name you want.
As we saw above, the basic for
loop has three parts: a starting point, an ending point, and an increment each time. Typically, we start at zero, end at some specific number, and count up by 1. The for
loop offers a lot of flexibility though. We can actually start and stop at any number and increment (or even decrement) with any interval.
Take a look at the following examples to see different ways to manipulate the basic for
loop. Notice how you can use basic math syntax to increment the loop variable (learn more about basic math in JavaScript here). Try to predict what each will print before running!
i
for each loop?i
for each loop?i
?Write a program that uses a for
loop to count by 5s up to 100.
When run, your output should look like this:
As you can see, for
loops make our lives as programmers much easier by making it easy to repeat code a specific number of times. So what can we do with for
loops other than print lines of numbers?
One thing we can do is loop over a set of data to determine a specific value, such as the sum or the product of all of the numbers. For example, the following code will loop over the numbers from the MIN
to the MAX
, adding each value to the variable sum.
Explore this program by changing the MIN
and MAX
values.
Write a program that finds the product of the numbers from 1 to 10, also known as the factorial of 10. You will need to use a variable to store the growing product. Hint: Think carefully about your starting value!
You’ve now mastered the basics of the for
loops - congratulations! But don’t stop here, there is so much you can do with for loops. Continue learning to discover things like nested for
loops and how to loop over data structures, such as arrays, strings, and lists.
You can also use for
loops for graphics. Check out this final example to see how you can use a for
loop to create graphics. Try changing the for
loop to create more layers in the rainbow!