Chapter 3. Changing Program Behavior with Conditions

In This Chapter

  • Generating random numbers and converting them to integers

  • Understanding conditions

  • Using the if-else structure

  • Managing multiple conditions

  • Using the switch structure

  • Handling unusual conditions

One of the most important aspects of computers is their apparent ability to make decisions. Computers can change their behavior based on circumstances. In this chapter you learn how to create random numbers in JavaScript, and several ways to have your program make decisions based on the roll of a digital die.

Working with Random Numbers

Random numbers are a big part of computing. They add uncertainty to games, but they're also used for serious applications like simulations, security, and logic. In this chapter, you generate random numbers to simulate dice and then explore various ways to modify the computer's behavior based on the value of the roll.

Most languages have a feature for creating random numbers, and JavaScript is no exception. The Math.random() function returns a random floating-point value between 0 and 1.


Technically, computers can't create truly random numbers. Instead, they use a complex formula that starts with one value and creates a second semi-predictable value. In JavaScript, the first value (called the random seed) is taken from the system clock in milliseconds, so the results of a random number call seem truly random.

Creating a die to die for

It's very easy to create a random floating-point number between ...

Get JavaScript® and AJAX for Dummies® now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.