Now you've learned something about the theory of JavaScript and what you can do with it, we will give you an idea of what the process of creating a simple JavaScript application is like by guiding you through a practical tutorial. In the last practice exercise, you'll build up a simple Guess the Number game step by step. The game uses "variables", "conditionals", "functions", "events", and "loops".
It is essential to practice "reading" a lot of code and running it when learning a new language. In addition, reading well-written code helps you write well-structured code. Don't worry about knowing events and built-in objects such as Math; we'll cover them in more detail in another course. This is a practice exercise, and if you can't get the game to work, check it against the source code.
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.