Prev <<   >> On to the next chapter: Caesar Cipher.


Guess My Number

Can you guess the computer's number? You get five tries:

An overview of the code:

  1. First we choose a secret number x and set up the turns counter and an initial hint.
  2. The following process is repeated while the turn counter is still positive:
    1. We show the hint and ask the user for a guess.
    2. We check if the guess is right (you win) or wrong (you need a new hint).
    3. The turns counter is decreased by 1, and we end the block and go back to repeat the loop.
  3. At the end the secret is revealed.

Control Flow with While, If, and Break

The program is a good example of the while and if statements.

The if statement checks the value of an expression in parentheses.

As you can see in other if statements here, the "else" clause is optional, and if the block of code after an "if" is only a single line, the curly braces may be omitted.

The while statement is similar to the "if" statement: when the expression in parentheses is true, the following block of code is run. After the block is finished, the "while" test is checked again, and as long as it is still true, the block is repeated.

It is possible to break out of a "while" loop without checking the test expression by executing the break statement inside the loop. This causes execution to jump straight out of the loop without checking or looping again. In our program this happens if somebody clicks "Cancel" or enters an empty guess into the prompt.

Strings and Numbers

Javascript works with two atomic types of data: Numbers and Strings.

Even though strings can contain digits, string arithmetic does not work the same as number arithmetic. For example, the following two expressions are both false:

Strings don't do mathNumbers don't concatenate
'4.0' == '4'   is false 12 == 1 + 2   is false

However, the following two expressions are both true:

Numbers do mathStrings concatenate
4.0 == 4   is true '12' == '1' + '2'   is true

Text input from a user arrives as a string, so if we want to work with a number, we need to convert it by using the Number constructor function:

var n = Number(text);

If the text happens to be not-a-number, then the number is converted to the special numeric value NaN which stands for "Not a Number". You can also get NaN by doing an illegal mathematical operation such as dividing by zero.

Comparison Syntax

Numbers can be compared in all the expected ways. Here is how mathematical comparison operators are written in Javascript:

x == 5The equality test operator is written with two equals symbols.
x != 5The inequality test operator is written with an exclaimation point before an equals symbol.
x < 5The strictly-less-than operator looks as you would expect
x > 5The strictly-greater-than operator looks as you would expect
x <= 5Less-than-or-equal-to is written with the equals sign last.
x >= 5Greater-than-or-equal-to is written with the equals sign last again.
!x"Not x" is true if x is false, or if x is 0, NaN, the empty string, null, or undefined.

Do not test equality with a single equals sign, because a single equals sign is only used to assign the value of a variable. (In other words, "x = 5" sets x to 5; it does not test whether x is 5.)

Using a single-equals assignment where a double-equals is needed is probably the single most common error that beginners make in Javascript.

Alert, Prompt, and Console Output

There are a couple odd and old-fashioned things about the Guess-My-Number program:

Try running the program again to see these limitations in action.

Although alert and prompt are old-fashioned and clumsy, they can be terrifically useful to use temporarily when debugging a program. If you are not sure what is going on in a program, you can insert an alert(x) call to announce a message or show the value of a variable at any time.

If you are using a browser with a debugger, console.log(x) can be used to print a message to the debugger's console without blocking the browser. This is even more useful than alert(x), but you need to be aware that console is undefined for browsers without debuggers.

On Chrome you can see the console by type Shift-Control-J. Try it out.

Guess Interactive

A more modern version of the program plays the game after the whole page is loaded by responding to events when the user submits guesses:

This code is similar to the first example, but the loop has been replaced by an event handler that is called whenever the <input> value has changed:

  1. First we choose a secret number x and set up the turns counter.
  2. Whenever the input is changed by the user, the following function is executed:
    1. Get the guess text and turn it into a number.
    2. Check the guess; if it is right then give a trophy and set turns to zero; if it is wrong then make a hint and decrease turns by 1.
    3. Check the turns: if turns is 0, then reveal the answer and hide the paragraph with the input field; if there are more turns, then tell how many turns are left.
    4. Update the display: put the hint text into the <div> and reselect the input text.

Four Phases of Event-Based-Programs

Using <input> fields instead of prompt and alert boxes makes the interaction part of the webpage so that it does not block the browser whenever we want to ask the user a question. However, writing a program to use <input> instead of prompt is a little bit more difficult and it takes some practice: the difference is that we must write event-based programs.

Event-based programs do the following:

  1. Draw a set of interactive elements on the page.
    Our program draws:
    1. A <div> for hints from the computer.
    2. A paragraph with an <input> box to accept guesses by the user.
  2. Listen for changes, clicks, or other relevant events that are fired by the elements.
    Our program uses $('input').change(...) to listen for changes to the <input> value.
  3. Run event handling functions to respond to events of interest.
    Most of the logic if our game is in the single anonymous event handling function passed as an argument to $('input').change(...). It reads the new guess from the user and then advances the game by one step.
  4. Respond by updating variables and elements on the page.
    Our event handling function:
    1. Updates the turns variable to track the progress of the game.
    2. Updates text inside the <div> to show the next message.
    3. Hides the paragraph with the <input> box when the game is over.


Prev <<   >> On to the next chapter: Caesar Cipher.