Project: Guess The Number Game

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.

Handling Events

 

At this point we have a nicely implemented checkGuess() function, but it won't do anything because we haven't called it yet. Ideally we want to call it when the "Submit guess" button is pressed, and to do this we need to use an event. Events are things that happen in the browser — a button being clicked, a page loading, a video playing, etc. — in response to which we can run blocks of code. The constructs that listen out for the event happening are called event listeners, and the blocks of code that run in response to the event firing are called event handlers.

Add the following line below your checkGuess() function:

guessSubmit.addEventListener('click', checkGuess);



Here we are adding an event listener to the guessSubmit button. This is a method that takes two input values (called arguments) — the type of event we are listening out for (in this case click) as a string, and the code we want to run when the event occurs (in this case the checkGuess() function). Note that we don't need to specify the parentheses when writing it inside addEventListener().

Try saving and refreshing your code now, and your example should work — to a point. The only problem now is that if you guess the correct answer or run out of guesses, the game will break because we've not yet defined the setGameOver() function that is supposed to be run once the game is over. Let's add our missing code now and complete the example functionality.