Chapter 2. Making Decisions with Conditions
In This Chapter
Generating random numbers and integers
Working with conditions
Using the if-else and switch structures
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 discover how to maximize this decision-making ability.
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, such as simulations, security, and logic. 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 zero and one.
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 an integer within a range
Creating a random floating-point number between zero and one is easy, thanks to the Math.random()
function. What if you want an integer within a specific range? For example, say that you want to simulate rolling a six-sided die. How do you get from the 0-to-1 floating-point value to a 1-to-6 integer?
Here's the standard approach:
Get a random float between ...
Get HTML, XHTML, & CSS All-in-One For Dummies®, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.