Guess

The concept of "guess" in programming often involves creating a game or function where the user attempts to determine a secret number. This can be a fun and interactive way to learn about conditional statements, random number generation, and user input handling in JavaScript.

Basic Guessing Game

A simple guessing game can be created using JavaScript, where the program selects a random secret number, and the user tries to guess it. If the user guesses correctly, the program responds with a congratulatory message. If the guess is incorrect, the program can provide feedback indicating whether the guess was too high or too low.

Example Code

Below is an example of a guessing game implemented in JavaScript:

Listing 12.1. Guess the number http://jsbin.com/feholi/edit?js,console Listing 12.1. Guess the number http://jsbin.com/feholi/edit?js,console

In this example, the getGuesser function generates a secret number between 1 and 10. The returned function takes a user's guess as input and checks it against the secret number using a series of conditional statements.

Neater Else-If Block

To improve the readability and structure of the code, an else-if block can be used. This allows for a more organized way to handle multiple conditions:

var getGuesser = function () {
    var secret = Math.floor(Math.random() * 10 + 1);

    return function (userNumber) {
        if (userNumber === secret) {
            return "Well done!";
        } else if (userNumber > secret) {
            return "Too high!";
        } else {
            return "Too low!";
        }
    };
};

var guess = getGuesser();

Console Interaction

When interacting with the guessing game in a console environment, you might see output like this:

> guess(2)
  undefined
> guess(8)
  Well done!
  undefined

The appearance of undefined is due to the function's return value being displayed in the console. If the function does not explicitly return a value, JavaScript automatically returns undefined.

Explanation

The guess function uses the strict equality operator === to compare the user's guess with the secret number. If the numbers match, the message "Well done!" is displayed. If the guess is incorrect, the function provides feedback on whether the guess was too high or too low, using an else-if structure to handle these conditions.