For Loops
Open the project folder
In our starter files, open the index.html page from this lessons folder:
06.Loops-and-conditionals > 01-For-loops
Why use loops?
When working with arrays earlier, we looked at some ways to repeat tasks using loops. The types we looked at were map()
and forEach()
.
Loops mean we can repeat tasks a lot easier. Even though there are different types of loops, they generally keep repeating a task several times. And often the main difference is how we tell it to stop.
These map()
and forEach()
loops were array methods, but loops are not exclusive to arrays. There are also different types of loops we can use.
The for
loop
You can try the following exmaples between the <script></script>
tags.
This section is going to be focusing on a for
loop. And this is how a basic for
loop looks:
for( ; ; ) {
}
It is set out a bit like a function or an if statement, notice inside of the brackets there are 2 semi-colons. These are used to pass in up to 3 expressions which declare how our loop will work.
A simple example is to increase a number, we will look at some better examples soon:
for(number = 0; number < 10; number++) {
}
- number = 0: This contains the initial or starting value for our loop. If we just want to start a number at zero and increase it each time, we set a variable to be zero like this. This initial value can be anything, any variable, and any type of data if we can do something useful with it in the loop.
- number < 10: This condition determines if the loop is to keep going. If this is true, the loop carries on, if false, it will end.
- number++: Lastly, if we don’t do something on each loop, the second condition will always be true, the number variable will always be zero. Here we increase the value of number by one, on each loop.
We can see the output in the console:
for(number = 0; number < 10; number++) {
console.log(number) // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
}
For this example the number
variable begins at zero, then on each loop it will be increased by one (number++
). Once number < 10
is false, the loop will end. Meaning this example will log ten values, 0 through to 9:
Declaring the variable outside the loop
If you have the variable already declared outside the for
loop, you can leave it out and just include the second and third statement:
let number = 0
for(; number < 10; number++) {
console.log(number) // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
}
Also, it is worth noting you will see lots of examples with the variable named the letter i
, which is short of initialiser or initial value. This generally happens if we are only using this variable for the purposes of the loop and not needing a descriptive variable name elsewhere. Note we must keep the semi-colons in place so we can clearly separate the three values.
Example
Onto some examples in the starter files:
// index.html
// 1. simulate somebody eating a pizza with ten slices
// deduct pizza slice after each loop
for (let slices = 10; slices >= 1; slices--) {
console.log(slices);
console.log("eat slice");
// equal to 1 not zero since slices-- runs before this code block
if (slices === 1) {
console.log("no slices left");
}
}
The console should look like this:
10
eat slice
9
eat slice
8
eat slice
7
eat slice
6
eat slice
5
eat slice
4
eat slice
3
eat slice
2
eat slice
1
eat slice
no slices left
The break
keyword
Something you may see but probably not as much is the second value missing, which is the condition:
for (let slices = 10; ; slices--) {
console.log(slices);
console.log("eat slice");
if (slices === 1) {
console.log("no slices left");
}
}
Do not run this code just yet!
Before we test this, you may be already spotting the problem. If we have no condition, we have no way of stopping the loop.
This is something we need to be careful of when creating loops. We must make sure the loops condition eventually becomes false, otherwise we would get an infinite loop, causing our browser to potentially crash.
To avoid this, we can manually use the break
keyword inside of the loop body when we want it to stop:
for (let slices = 10; ; slices--) {
console.log(slices);
console.log("eat slice");
if (slices === 1) {
console.log("no slices left");
break;
}
}
Creating multiple elements
Another useful thing we can do with loops is to create multiple elements, such as list items. Using a loop we can create many HTML elements with much less code:
const ul = document.createElement("ul");
document.body.appendChild(ul);
for (let i = 1; i <= 10; i++) {
const li = document.createElement("li");
const text = document.createTextNode(`list item ${i}`);
li.appendChild(text);
ul.appendChild(li);
}
- We create an empty ul element outside of the loop.
- A for loop is set to run ten times. Each one creating a new list item, the text content will be numbered one onwards as the loop increases.
- Each list item is then added to the ul after it is created.
- The new ul is added to the body to render in the browser.
Try this out, much quicker than creating ten elements manually!