Project: Guess The Number Game
Adding a Loop
One part of the above code that we need to take a more detailed look at is the for loop. Loops are a very important concept in programming, which allow you to keep running a piece of code over and over again, until a certain condition is met.
To start with, go to your browser developer tools JavaScript console again, and enter the following:
for (let i = 1 ; i < 21 ; i++) { console.log(i) }
What happened? The numbers 1
to 20
were printed out in your console. This is because of the loop. A for
loop takes three input values (arguments):
- A starting value: In this case we are starting a count at 1, but this could be any number you like. You could replace the letter
i
with any name you like too, buti
is used as a convention because it's short and easy to remember. - A condition: Here we have specified
i < 21
— the loop will keep going untili
is no longer less than 21. Wheni
reaches 21, the loop will no longer run. - An incrementor: We have specified
i++
, which means "add 1 to i". The loop will run once for every value ofi
, untili
reaches a value of 21 (as discussed above). In this case, we are printing the value ofi
out to the console on every iteration usingconsole.log()
.
Now let's look at the loop in our number guessing game — the following can be found inside the resetGame()
function:
const resetParas = document.querySelectorAll('.resultParas p');
for (let i = 0 ; i < resetParas.length ; i++) {
resetParas[i].textContent = '';
}
This code creates a variable containing a list of all the paragraphs inside <div class="resultParas">
using the querySelectorAll()
method, then it loops through each one, removing the text content of each.