A for loop is most useful when you do know how many times you need to run through a loop.
We need the three essential parts of a loop: the initializer, the loop condition, and the way to make the condition false (called an incrementer here).
This has all the three main parts up in the declaration. It's not like a while loop that needs to be initialized outside the loop and have the condition changed inside the loop. The for loop takes care of all of that all at once.
Notice the use of semicolons here. Do not put one outside the parentheses or the code below won't loop.
This prints 0
through 9
to the console. Let's break down the parts.
for ( )
let i = 0;
i
beforei
is often used as the variable but we could use counter or anything meaningful0
, but many loops doi < 10;
i++
i
by 1
i += 2
, i = i * 5
, etc.i--
, i = i - 3
, etc.{
//code
block
}
This starts at 0
and counts up by one each time through the loop. It prints to the console and at the
end of the code block, the index increases by one. The loop runs over and over until the index i
reaches 10
. It exits the loop without running the code block that last time.
Let's mix it up a little so we don't always have everything going in the same exact order for each example. I'm going to change a bunch of things here. See if you can figure out what the result will be. Here it goes.
Can you figure out what the output will be?
First, I declared the index variable, socks
, before the loop. I didn't do this for any reason other
than just to show you that it can be called something else and that you can declare it outside the loop.
One reason you might do this is if you're going to use this variable in a few loops going forward. You won't have to declare it each time; you can just reuse it. This is a memory-saving feature. By reusing the variable, you technically save memory. But unless you're making crazy huge programs, you won't have to worry about this in JavaScript. Memory allocations get handled automatically and if a variable is no longer needed, it gets garbage collected or erased from memory.
You can declare as many variables as you need, even within a loop. If you ever run into memory issues, then go back and tidy that up. Again, you'd have to be making tons of variables and have lots of intense calculations happening to have to worry about that.
Next, I initialized the starting point of the loop to 20
.
We are running the loop as long as the index (socks
) is greater than zero 0
. If we were
counting up in positive numbers, this would give us an infinite loop in this example.
The incrementer is socks -= 2
. This is shorthand for socks = socks - 2
. In other words,
socks
will decrease by 2
each time the code block finishes.
Put all of that together. What values of socks
will be displayed?
Well, we start at 20
and count down by 2
as long as we're greater than 0
. So
20
, 18
,... 6
, 4
, 2
. And that’s it. We won't get
0
, because we set the conditional as socks > 0
, not socks >= 0
.
What is the value of socks
after the loop is finished? Still 2
? Check it out in a console
window. Run the loop and then type socks
in the console. You may be surprised, but the value is
0
! It didn't display that, though, because as soon as it hit that value, it exited the loop.
There are two other major uses of a for loop. These have their own tutorial pages.
Arrays are lists. They have elements in those lists. They're just like a shopping list, or a list of toys, or a set of cars in a parking lot.
We can use a for loop (or a special array method, .forEach
)
to access each element in the array and do something with it. Check out Looping Through
Arrays for more detail.
Objects are a major part of JavaScript programming. They're used to keep details together for individual things (objects!). An object could have properties related to a car (make, model, year, etc.), or a weapon in a video game (attack power, element, status effect, name), and so on.
You may need access to the different properties in the object. For this, you need a special version of a for loop, called a for...in loop. Check out For...in Loop for Properties for more information.