O'Reilly logo

JavaScript® and AJAX for Dummies® by Andy Harris

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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.

Note

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required