Skip to content

Numbers, Math, and Randomness: Building a Guessing Game

Programming Node.js Difficulty 1/5

Beginning of the lesson

Numbers, Math, and Randomness

Understand how JavaScript really counts, dodge the classic number bugs, and build a fun guessing game.

Big Idea: In JavaScript, every number - whether it looks like a plain whole number or a decimal - is stored the same way. That one choice explains almost every "weird number" surprise you will ever meet. Once you understand it, you can predict the surprises instead of being tricked by them.
By the end you will be able to:
  • explain why JavaScript has just one kind of number,
  • understand why 0.1 + 0.2 is not exactly 0.3,
  • round numbers safely and handle money without bugs,
  • recognise NaN and check for it correctly,
  • use the Math object and generate random numbers in a range,
  • put it all together in a number-guessing game.

One number type to rule them all

Many languages have two separate kinds of numbers: integers (whole numbers like 7) and floating-point numbers (decimals like 3.14). JavaScript, the language Node runs, keeps things simple on the surface: there is just one number type, called number. Whether you write 7 or 3.14, Node stores both as the same kind of value - a 64-bit floating-point number.

Analogy. Imagine a ruler that can measure any length, but its smallest marks are tiny fixed steps. Whole centimetres land exactly on a mark, so they are perfectly precise. But a length like "one third of a centimetre" falls between two marks, so the ruler has to pick the nearest mark - close, but not perfect. JavaScript numbers work the same way: whole numbers up to a very large size are exact, but many decimals can only be stored as the nearest available value.

You can check the type of any value with typeof:

typeof 7        // "number"
typeof 3.14     // "number"
typeof -0.5     // "number"

All three are the same type. There is no separate "int" or "float" - just number. This makes beginner code simpler, but it is also the root of the surprises we will meet next.

Continue this lesson on YourAIZone

The full lesson has the complete explanation, worked examples, common mistakes, tests with instant checking and an AI tutor. Start right away as a guest, or create an account to keep your progress.

In the full lesson

  • The complete explanation
  • Worked examples
  • Common mistakes and how to avoid them
  • Test questions: 15
  • AI tutor that answers questions about the topic
  • Progress tracking for students, parents and teachers