Bo dinglesTM - -   Bright Lightbulb Graphic Ideas   - -

The Web Developer Bootcamp 2024

Colt Steele

Back to JavaScript Index Page


Random Numbers & Math Objects

Math Objects contain several properties and methods for mathematical constants and functions. Math Objects allow you to perform mathematical tasks on numbers. Unlike other objects, the Math object has no constructor. The Math object is static. All methods and properties can be used without creating a Math object first.

More info at W3Schools and MDN.

some examples:

  • Math.PI returns 3.141592653589793
  • Math.round(4.9) returns 5
  • Math.abs(-456) returns 456
  • Math.pow(2,5) returns 32 (2 to the 5th power)
  • Math.floor(3.99999) returns 3 (removes the decimal point and everything after it)


Random Numbers

Math.random() gives us a random decimal between 0 and 1 (non-inclusive : will not include 1).

examples:

  • Math.random() = 0.34658374517867085
  • Math.random() = 0.17166638184995286
  • Math.random() = 0.12029235693744655
  • Math.random() = 0.3359941706194536


So you generate a random number between 0 and 1.

  • Math.random()
  • returns a number between 0 and 1, not including 1
  • 0.34658374517867085

What if you want a number between 0 and 10?
*note: 10 could be any number. It would the higest number for your random range (non-inclusive)

  • do random number * 10
  • Math.random() * 10
  • 3.4658374517867085

If you don't want the decimal numbers?

  • do a Math.floor() on random number * 10
  • Math.floor(Math.random() * 10)
  • 3

What if you don't want the 0, just between 1 and 10?

  • do (random number * 10) + 1
  • Math.floor(Math.random() * 10) + 1
  • 4

What if I want a range of say 20 to 23?
- first we figure out how many random numbers we're gonna need
- 20, 21, 22, 23 : that's 4 numbers we want to randomize
- so our maximum random number is 4

  • do (random number * 4)
  • Math.floor(Math.random() * 4)
  • because we want the random process to start at 20, we add 20 to the random number generated
  • Math.floor(Math.random() * 4) + 20
  • 22


In summary, the formula is (Math.random() * how many numbers) + randomization start.
- Randomization start determins where the randomization starts
- How many numbers determins how many numbers are to be randomized

So:
a random number between 0 and 1(non-inclusive) would be Math.random()
a random number between 0 and 10 would be Math.random() * 10
and a random number between 15 and 25 would be (Math.random() * 10) + 15 : (10 numbers to randomize starting at 15)


Back to Top