Happy Learn JavaScript Tutorial Vol 1

Please Buy now at Leanpub

Written and illustrated by GetContented.

Published on 2016-05-22.

Contents

Making a simple guessing game, we’ll introduce objects, setting & retrieving properties on objects, calling methods on objects, the Math object, Math.floor , Math.random , the if statement and conditionals.

Our game will make up a secret number, and we’ll take some turns guessing it. Make a new file called guessing_game.html and open it in our browser.

Javascript has a concept called objects, which is a way of bundling a bunch of named values into a single value. For example, we might decide to model some information about Angelina Jolie:

<html> <body> <script> var angelina = { firstName: "Angelina", lastName: "Jolie", born: 1975 }; </script> </body> </html>

This program simply creates a variable called angelina which is an object that bundles three properties together, named firstName , lastName and born . The fancy squiggly brackets (called braces) are how you define an object literal in JavaScript. Each named place for data in an object is called a property of the object. The properties are written as name-value pairs, and are separated from each other by commas. Each property has a name, then a colon and then its value. This is kind of like having a bunch of variables inside a variable!

If we want to get one of the property values out, we can do so pretty easily by using a dot and its name, like this:

<html> <body> <script> var angelina = { firstName: "Angelina", lastName: "Jolie", born: 1975 }; alert(angelina.firstName + " " + angelina.lastName + " was born in " + angelina.born); </script> </body> </html>

Running this will alert "Angelina Jolie was born in 1975" . So you can use angelina.firstName to get the data out of the firstName property of the angelina object. This works for whatever the property is named. You can also use angelina.lastName = "Angoyloona" to set the last name to something else (Angoyloona here). This will actually change the value of the lastName property of the object.

Functions are also values, so if an object’s property is a function, it’s called a method and we can call it just like a regular function. We can retrieve it using the same syntax that we saw for retrieving property values, but if we add parentheses to the end, we can call it just like any function.

Ok, that’s enough to do with Angelina.

JavaScript has a whole range of objects built into it with properties and methods for doing all kinds of things.

For our guessing game we’re going to use an object called Math that has a method called random . Each time random is called, it will return a new random number value between 0 and 1 (but never actually 1 ).

Let’s see a program that alerts a random number every time you refresh the page:

<html> <body> <script> alert(Math.random()); </script> </body> </html>

Try it out a few times, by loading then reloading the page.

We’d like our program to give us a number between 1 and 10 , so let’s start see how to build toward this functionality.

By using the * operator to multiply the result of random by 10 — we can call this “scaling” the result — we can get a number between 0 and 9 . We’ll use some variables to show our steps, too:

<html> <body> <script> var secret_float = Math.random(); var secret_float_scaled = secret_float * 10; alert(secret_float_scaled); </script> </body> </html>

Why name them float? Well, these numbers are called floating point numbers, it’s just the name of the type of numbers, they’re sort of like decimals, but less accurate. Our number is scaled by a factor of 10, then displayed as an alert.

Ok this number is between 0 and 9, so we have to add one to get it between 1 and 10. We’ll call this shifting it, and name our variable accordingly:

<html> <body> <script> var secret_float = Math.random(); var secret_float_scaled = secret_float * 10; var secret_float_scaled_shifted = secret_float_scaled + 1; alert(secret_float_scaled_shifted); </script> </body> </html>

If you want to, reload the page with this new program until you’re confident it’s giving us different numbers between 1 and 10.

Ok, but we don’t actually want the numbers after the decimal point. Removing them can be done by another method of the Math object called floor , which will take anything after the decimal point and round it down to zero. This means we now have the secret number we want for our guessing game!

<html> <body> <script> var secret_float = Math.random(); var secret_float_scaled = secret_float * 10; var secret_float_scaled_shifted = secret_float_scaled + 1; var secret_number = Math.floor(secret_float_scaled_shifted); alert(secret_number); </script> </body> </html>

Ok we’ll stop at this point and do some of what’s called refactoring. This is where we improve the way the code works. In our case, we’ll collapse the four lines into one single variable assignment and expression, for simplicity:

<html> <body> <script> var secret_number = Math.floor(1 + Math.random() * 10); alert(secret_number); </script> </body> </html>

This is an expression that does all of the previous code in one single step. It calls Math.floor on the result of calling Math.random , multiplying by 10 and adding 1 to it. We can do this because each expression results in a value, which in turn is fed in as argument(s) to another function or expression.

Now we can ask the user for their guess:

<html> <body> <script> var secret_number = Math.floor(1 + Math.random() * 10); var guess = prompt("Guess a number between 1 and 10"); </script> </body> </html>

We want the computer to tell the user if they got the answer right. To do this, we’ll see a new statement called the if statement.

<html> <body> <script> var secret_number = Math.floor(1 + Math.random() * 10); var guess = prompt("Guess a number between 1 and 10"); if(guess == secret_number) { alert("You got it!"); } </script> </body> </html>

We can see that if looks similar to a function call, except it has some braces afterward that are wrapping a statement with a call to alert in it. The if statement is how we can get our program to check the truth of something, such as an expression, and do different things depending on that check.

We can put as many statements as we like within these braces. These are not being used to show an object definition here, they’re the same type of braces, but they’re doing something different: they’re being used to create a block of code. That is, this if statement will test the expression within its parentheses and if that expression evaluates to true , it will execute the block of code that follows it in sequence. If the test expression is false , it won’t do anything.

Here we’re using the == operator, which tests whether the expression on its left is equal to the expression to its right. Here that means if guess is equal to the secret number!

When you play this game, you’ll quickly realise it’s no fun: we only get one chance, and it doesn’t tell us when we’re wrong. Let’s make it more playful.

There is more to the if statement... we can use an else statement on the end to indicate what the program should do if the test fails.

Let’s put something telling us what the number was when we were wrong. This won’t make it any more fun, but we’ll get to that.

<html> <body> <script> var secret_number = Math.floor(1 + Math.random() * 10); var guess = prompt("Guess a number between 1 and 10"); if(guess == secret_number) { alert("You got it!"); } else { alert("Wrong. The number was " + secret_number); } </script> </body> </html>

So if the test expression evaluates to false , the second block of statements executes. If it evaluates to true , the first block executes.

Notice we’ve also added another variable but set it to null for now, called guess2 . We’re going to embed another guess in the failing block, which will mean we can give the user a second chance at guessing. Don’t be worried, we’ll explain how it works:

<html> <body> <script> var secret_number = Math.floor(1 + Math.random() * 10); var guess = prompt("Guess a number between 1 and 10"); var guess2 = null; if(guess == secret_number) { alert("You got it!"); } else { if(guess < secret_number) { guess2 = prompt("Guess a number between " + guess + " and 10"); } else { guess2 = prompt("Guess a number between 1 and " + guess); } if(guess2 == secret_number) { alert("You got it!"); } else { alert("Wrong. The number was " + secret_number); } } </script> </body> </html>

If you try this program out a few times you’ll realise while it’s still hard, it’s actually possible to guess now, because this program gives you a second chance, and tells you which side of your guess the secret number is on after your first guess.

If we just look at the block inside the first else , we’ll see there are two if ... else statements. The first compares the guess to the secret and gives the user a different prompt depending on the answer, and the second if ... else statement gives them their results.

Notice that the last two if ... else statements and their blocks are all included within the first else block?

Blocks can contain other blocks just fine, and can have more than one statement inside them, too.

The if statement is one example of what’s called a conditional, which means it changes what the program does depending on some values or other expressions.

Your homework is to type each of these programs in and try them out. Also, notice in the secret_number expression, the * operator is performed before the + operator, because of order of operations, just like in arithmetic in maths.

The second part of your homework is to try, without looking, to create a single line program that puts a message window on the screen with a greeting on it, similarly to what we saw in the “Display a Message” chapter. Try to do it without looking it up. If you have to look, do it while looking, but then try again in an hour or so. We’re trying to connect up making a single line program into your memory. Try as many times as you need to until you can do it without looking at all.

The third part of your homework is to make a single line program that displays a message on the screen, but to then try to break it in as many ways as you can think of. See what happens when you miss pieces off, or when you do crazy things to your program. Get familiar with all the ways you can fail. If we make failure our friend, it won’t be so bad when we unexpectedly see it in a program, because we’ll already have lots of experience with all the ways things can go wrong. This is the mark of a master.

If you’ve enjoyed reading this, please consider purchasing a copy at Leanpub today

Please follow us, and check out our videos Follow @HappyLearnTutes