JavaScript for Absolute Beginners 3

In this tutorial, we’re going to write a number guessing game using JavaScript.



Other tutorials of this series.

Notes for this tutorial:

Task for this tutorial: Write a JavaScript program to

  • Generate a random secret number ranged from 0 to 100
  • The program will tell the player the range and the player has to guess the number
  • The range will be narrowed until the player make a correct guess

Genrate a random number between 0 and 100 (inclusive)

Genrate a random number
1
2
3
//Math.random() returns a number between 0 (inclusive) and 1 (exclusive)
//Math.floor() returns the floor of a number, e.g. 4.56 => 4
const secret = Math.floor(Math.random() * 100) + 1;

Math operators

Math operators
1
2
3
4
5
6
7
let num = 2+3; //add
num = 2-3; //subtract
num = 2*3; //multiply
num = 3/2; //divide
num++; //increment
num--; //decrement
num = (3+2)*5; //Operator precedence

Functions

Functions
1
2
3
function multiply(a, b) { //a and b are parameters
return a * b; //return value
}
  • parameter
  • return value
  • scope of variables

Error (exception) handling

Error handling
1
2
3
4
5
6
7
8
9
function someFun() {
throw new Error("error message");
}

try {
someFun();
} catch (e) {
console.error(e.message);
}

Check for equality

Check for equality
1
2
3
4
5
const a = "foo";
const b = "bar";
if (a === b) { //Use 3 equality signs to check for value equality and type equality
//...
}

Algorithm

  • Binary search
  • Time complexity \(O(\log n)\)

The source code of the program in this tutorial on GitHub.