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.

Adding a Function

 

Next, add the following below your previous JavaScript:

function checkGuess() { alert('I am a placeholder'); }



Functions are reusable blocks of code that you can write once and run again and again, saving the need to keep repeating code all the time. This is really useful. There are a number of ways to define functions, but for now we'll concentrate on one simple type. Here we have defined a function by using the keyword function, followed by a name, with parentheses put after it. After that we put two curly braces ({ }). Inside the curly braces goes all the code that we want to run whenever we call the function.

When we want to run the code, we type the name of the function followed by the parentheses.

Let's try that now. Save your code and refresh the page in your browser. Then go into the developer tools JavaScript console, and enter the following line:

checkGuess();



After pressing Return/Enter, you should see an alert come up that says I am a placeholder; we have defined a function in our code that creates an alert whenever we call it.