Learn To Code Part IV: Understanding Functions And Making A Guessing Game

If you’ve made it this far in our programming lessons, you’ve arrived at the reward. Today we’re learning about functions and then we’re going to make a very simple guessing game.

These lessons work best with the video, which you can see above, but we’re also providing text for reference below. Even if you do prefer to read, the videos will be more explicit and demonstrate how to do everything we’re discussing. If the text seems a bit too complicated, be sure to watch the video.

Today is our last-ish lesson (there will be an “epilogue” with a mini-lesson on best practices and additional resources following this one), and we’re going to cover two things: functions and making a very simple guessing game. If you made it through Lesson 3, chances are you’ll find functions pretty easy to learn. We’re going to tackle that first and then use that knowledge—plus a little HTML—to put the game together.

What The F Is A Function?

Oh, come on, you already know all about functions. You’ve been using one this entire time: alert(). A function is basically a means of calling a large chunk of code with just a tiny bit of text. Functions are kind of like the text expansion of programming. While you’ve used alert(), that’s just a built-in function (of which there are many in JavaScript and all modern object-oriented programming languages). Today, we’re going to create our own function that will eventually help us make a guessing game. First, let’s take a look at how a function is declared in your code:

function nameOfFunction(variables)

{
}

This should look pretty familiar. Functions look a lot like for loops and if statements. Let’s break down what we’re looking at. First, we start with the word function to tell the computer that we’re defining a function. Next we have to name that function. In this example it’s titled nameOfFunction but you’d normally name it something relative to what it does (like how alert() creates an alert dialogue box when used). After the name of the function are parentheses. You’re not required to put anything inside the parentheses, but if you need to give the function some information (which is called passing it variables/a variable) you need to specify the name of the variables that you’ll be using inside of the function. This might be a little confusing right now, but we’re going to look at it a bit more later so don’t worry. Finally, we have our curly braces at the end. Everything the function needs to do will go inside of these curly braces.

Now that you know how a function is defined and what it does, let’s put it to use!

Making A Simple Guessing Game In JavaScript

There are two parts to this process: the function and the interface (which is basically a form where the user can enter a number). First, we’ll start with the function.

Making the Function That Runs Your Game

To make the game, we’re going to need to make a function that reacts to user input. Let’s put together a function that does that:

var perfectNumber = 12;

function checkApples(numApples)
{
if (numApples == perfectNumber)
{
alert(“You ate the perfect number of apples!”);
}
else if (numApples > perfectNumber)
{
alert(“You ate way too many apples.”);
}
else if (numApples < perfectNumber)
{
alert(“You didn’t eat enough apples.”);
}
}

Okay, that’s a lot to look at so let’s break it down. First, I created a variable called perfectNumber and set it to 12. This is the number the user is going to try to guess in our game. You can set this number to anything you want, and if you want a few bonus points you can try implementing this randRange() function to randomise the number each time the page loads—but let’s do the basic stuff first.

After the variable perfectNumber is defined, we’re creating a function called checkApples and passing it a variable called numApples. This means that when we call this function we’ll need to give it a number, which would look something like checkApples(5). That number is going to come from the user, however, so we’re not going to talk about that just yet.

Inside the function is an if statement with three conditions. The first condition checks to see if numApples—the number variable passed to the checkApples function—is equal to perfectNumber—the variable we set earlier (that’s the answer the user will be trying to guess. If that condition is met, the user will get an alert that congratulates them on choosing the correct number. If not, the second condition will check to see if they guessed too high. If they guessed a number larger than perfectNumber they’ll be alerted that they ate too many apples. Basically the same thing happens with the third condition, but they’ll be alerted if their guess is too low.

That’s all there is to the function, and it’s pretty simple. But how do we request a number from the user? That’s going to require combining a little JavaScript with a little HTML.

Making A User Input Form

Making a form is something you might’ve done before if you’ve ever used HTML. It’s pretty easy. First, you’ll need to put this in the <body> of your HTML document:

<form>
<inputtype=”text”name=”numApples”id=”numApples”/>
<inputtype=”Submit”name=”Submit”/>
</form>

That will get you a super simple form with a text box and a submit button, but it won’t do anything. First, we need to add some stuff to the form tag to connect the input to your checkApples() function:

<formmethod=”POST”name=”applesForm”onSubmit=”checkApples(document.applesForm.numApples);”>

So what did we just add, exactly? First, we told the form to use the POST method. This isn’t terribly important because it’ll work either way, but the POST method is a bit cleaner for what you’re doing here. POST won’t put all the variables submitted in a form into the URL, but GET—your other option—will. Second, we named the form applesForm because we’re going to need to refer to it by name when specifying where the user input text box is in the document. Lastly, we have something called onSubmit which lets us execute some JavaScript code when the submit button is pressed. In most forms there would also be a property called action, telling the form where to go after submitting, but we just want to stay on the page so we don’t need it. Getting back to onSubmit, you can see we’ve basically set it to the checkApples() function. Instead of giving checkApples() a number, however, we’ve given it document.applesForm.numApples.value. This is how we’re referencing the user input text box in our form. We’re doing this by using the Document Object Model, or DOM, in JavaScript. Let’s break this down:

  • document – Your HTML document.
  • applesForm – The name of the form we created.
  • numApples – The name of the text field we created for user input, which is inside of the applesForm.
  • value – We don’t want the text field we created, but what’s inside of the text field. You need to attach value to the end of a text field so you can get the value of it and not a reference to the text field object that contains it.

Once you’ve got all of this in your code, you’re done! Save the page, reload it in the browser, and try guessing your number. Aim too high, too low, and then guess it correctly. You should find that you get the responses you defined in your code alerted to you each time you guess. So, congratulations, you just made your first game!

It’s Almost Time To Say Goodbye

Well that about does it for our basic coding lessons. We hope you’ve enjoyed them and feel ready to approach more complicated stuff as you begin your foray into the programming world. By popular demand, we’ll be doing one more post tomorrow about a few programming best practices—mainly commenting your code—as well as including additional resources to help you learn more about everything we’ve discussed and where to go next.


The Cheapest NBN 50 Plans

Here are the cheapest plans available for Australia’s most popular NBN speed tier.

At Lifehacker, we independently select and write about stuff we love and think you'll like too. We have affiliate and advertising partnerships, which means we may collect a share of sales or other compensation from the links on this page. BTW – prices are accurate and items in stock at the time of posting.

Comments


One response to “Learn To Code Part IV: Understanding Functions And Making A Guessing Game”

Leave a Reply