01219245/javascript1/tutorial1

จาก Theory Wiki
ไปยังการนำทาง ไปยังการค้นหา
This is part of 01219245

The best way to learn a language is to use it.

In this tutorial, we will write a simple number guessing game in JavaScript. Your goal is to guess a number between 1 - 100. If you guess incorrectly, a hint is given to you: if your guess is too high or too low. The game proceeds until you guess correctly.

An example of the interaction is given below:

Round 1, your guess?
40
Too low.
Round 2, your guess?
90
Too high.
Round 3, your guess?
75
Too high.
Round 4, your guess?
55
Great that's correct.

Let's get started

Before we dive in to code the game, it's best to think about the overall picture. We code in small steps, but without the overall idea, it is very easy to get lost.

What are the steps, in the program, that we have to do?

  • Random the number
  • Read the guess
  • Check the guess and give hint
  • Repeat

First sketch

If we forget all the details, our JavaScript program would look like this:

var sol = randomSolution();
do {
    var guess = readGuess();
    if ( guess == sol ) {
        congratulate();
    } else if ( guess < sol ) {
        giveHint( 'Too Low' );
    } else {
        giveHint( 'Too High' );
    }
} while ( guess != sol );

This looks like a Java program! The control statements (if and do-while) should look familiar. There are things that look like methods randomSolution, readGuess, congratulate, and giveHint. We have two variables sol and guess. If you come from Java, you should see a major difference now.

A dynamic language

In Java, you declare a variable with its type. For example, you may say int sol;. However, in JavaScript, we do not specify variable's type; we only use keyword var to declare a local variable. It is not that data in JavaScript do not have types; they do. But the type information is in each piece of the data itself, not in the variable that keeps it.

In Java, you cannot do this:

  int a = 10;
  a = "dog";      // wrong type for variable a

But it is perfectly fine in JavaScript:

  var a = 10;
  a = "dog";     // ok.  (but this is not a good practice)

(However, it is not a good practice to do so.)