Step 6: For Loops
Coding is great because it makes it easy to automate boring tasks, like writing the same thing over and over again. A "for loop" lets you do that in JavaScript. For loops basically let you perform the same operation a certain number of times, each time with a different value.
A for loop has the following syntax:
Statement 1 defines a variable for the loop. It is usually a number, which we will increase each time the loop finishes so we can keep track of where we're at. You can set the number to be whatever you want, but usually you will start at 0.
Statement 2 defines how long the loop will go on for. It most often uses the less than (<
) or less than or equal to (<=
) operators to set the length.
Statement 3 defines how much to increment the i
variable by each time. If you just want it to increase by one, then put i++
(this is the shorthand for i = i + 1
), or else you can increase by other numbers like so:
Inside the curly brackets goes the code you wish to be executed each time the loop runs. You can refer to the variable i
from inside the loop.
Try it out
Here's an example of an actual for loop that prints out the numbers 1 to 10:
Notice the variable i
is set to 1
, because we want counting to begin at 1. The length is set to be less than or equal to 10, as we want the loop to end there. And we are increasing the value of i
by one each time.
Last updated