Back To Course

Introduction to JavaScript8 chapters | 39 lessons

Instructor:
*Amit Agrawal*

Amit has over 11 years of industry experience in the IT Software Domain and has a Masters Degree in Computer Applications.

In this lesson, you will learn how to generate random numbers in JavaScript. You will learn why random is not always random in computer programming and see many relevant examples.

It may come as a surprise but computers cannot generate a truly random number! This is because computers are, by their very design, deterministic machines. What this means is that they perform whatever operation you give them exactly as told. So, if told to add two numbers, the result will be exactly that, not a bit more, not a bit less. This is certainly what we expect them to do in the first place. Unfortunately, this means that generating truly random numbers is impossible.

For a number to be random, there has to be absolutely no way to predict it. Since this is impossible using computers, random numbers are generated using a statistical algorithm that takes an initial input number, known as a seed number. Based on this seed number, it generates numbers that seem random and unpredictable using mathematical formulas. Such algorithms are known as Pseudo-Random Number Generators (PRNG). Good algorithms generate numbers that approximate the properties of random numbers. For most purposes, random numbers generated in this fashion are quite acceptable and all the software that you use on a daily basis that needs random numbers internally uses them perfectly well.

Random numbers generated using PRNGs are based on a starting seed value. Thus, say you use a seed value of 87, the first ten random numbers that come out of the generator could be 5, 23, 89, 32, 47, 51, 9, 76, 64 and 13. Similarly, say you use another seed value of 34, the first ten random numbers out of the generator could be 45, 22, 63, 75, 12, 87, 54, 27, 98 and 23. Of course, we have taken just the first ten random numbers using both these seed values and both the sequences don't repeat. In fact, the algorithms are designed very carefully to produce extremely large sequences without repetitions, which is perfectly fine for most applications.

As you saw above, both sequences seem random but since they follow a precise mathematical algorithm to generate them, if you use the same seed number, they will produce exactly the same sequence of random numbers each time! Internally, the mathematical algorithms take the seed value, run it through the formulas, and generate an output number that is used as the first ''random'' number, which is then used to generate the next ''random'' number, and so on. They generate the exact same sequence each time for a given seed value. So, how do you choose a random seed in the first place? Programmers faced with this dilemma try to get something from the environmentâ€”the time of the day, or the wait time between two keypressesâ€”you get the idea! Of course, even these are not truly random since you could have a program that is scheduled to run at exactly the same time every day, but we have to start somewhere! It is extremely difficult to get genuinely random numbers in the world of computers.

JavaScript has a built-in function that generates pseudo-random numbers, Math.random(), which returns a floating-point number between 0 and 1. To be precise, it can return a 0, but never 1. You can then use this to get a range of numbers of your choice. The initial seed value to the pseudo-random number algorithm that this function uses is chosen by JavaScript and cannot be provided by the user.

Here are some numbers generated by calls to Math.random():

0.6334925574662507

0.8321259561285135

0.2348479346493022

0.18391458658126458

0.4788609282531491

0.14444213567234

0.47212191409546134

0.9359784877972861

Since all of the numbers generated are between 0 (inclusive) and 1 (not inclusive), we need a way to convert them into integers, or to fall within a range that we need for the program we are writing. For example, a roll of dice should be a perfect integer within a range of 1 and 6. As another example, for GPS latitudes, our need could be between 12.55555 degrees to 27.43505 degrees.

Let's create a function that takes two arguments, the minimum and the maximum (both inclusive) and spits out a random integer between the two.

`function randInt(min, max) { `

` return Math.floor(Math.random() * (max - min + 1)) + min; `

`} `

Let's assume the user enters integer numbers for the two inputs and we want to return a random integer within that range. We know that the random function returns a decimal value between 0 (inclusive) and 1 (not inclusive). If we assume it returns 0, then we want to return the min value and similarly, if it returns 0.9999999 i.e. close to 1, then we want to return the max value. For any other value that the random() function returns, we want it to pick a number between this range. This is exactly what the Math.floor(Math.random() * (max - min + 1)) + min does. Here's some sample output:

`randInt(1,6) `

`3 `

`randInt(1,6) `

`1 `

`randInt(1,6) `

`6 `

Let's create a function that takes two arguments, the minimum and the maximum, and spits out a random decimal value which is greater than or equal to the minimum but lesser than the maximum.

`function randDec(min, max) { `

` return Math.random() * (max - min) + min; `

`} `

We know that the random function returns a decimal value between 0 (inclusive) and 1 (not inclusive). If we assume it returns 0, then we want to return the min value. On the other hand, if it returns 0.9999999 i.e. close to 1, then we want to return a value close to the max value. For any other value that the random() function returns, we want it to pick a number between this range. This is exactly what the Math.random() * (max - min) + min does. Here's some sample output:

`randDec(12.55555, 27.43505) `

`12.763453423 `

`randDec(12.55555, 27.43505) `

`12.555555000 `

`randDec(12.55555, 27.43505) `

`27.435049999 `

Computers are designed to be deterministic machines. This means that generating truly random numbers is impossible using a computer. For a number to be random, there has to be absolutely no way to predict it. In computers, random numbers are generated using special statistical algorithms and mathematical formulas that take an initial seed number. Such algorithms are known as Pseudo-Random Number Generators (PRNG). Good algorithms generate numbers that approximate the properties of random numbers. PRNGs are designed very carefully to produce extremely large sequences of random numbers without repetitions, which is perfectly fine for most applications that need them. If you use the same seed number, PRNGs will produce exactly the same sequence of random numbers each time because they follow a precise mathematical algorithm to generate them.

JavaScript has a built-in function that generates pseudo-random numbers, Math.random(), which returns a floating-point number between 0 and up to 1 (but never 1). The initial seed value to the pseudo-random number algorithm that this function uses is chosen by JavaScript and cannot be provided by the user.

To unlock this lesson you must be a Study.com Member.

Create your account

Are you a student or a teacher?

Already a member? Log In

BackWhat teachers are saying about Study.com

Already registered? Login here for access

Did you know… We have over 160 college courses that prepare you to earn credit by exam that is accepted by over 1,500 colleges and universities. You can test out of the first two years of college and save thousands off your degree. Anyone can earn credit-by-exam regardless of age or education level.

To learn more, visit our Earning Credit Page

Not sure what college you want to attend yet? Study.com has thousands of articles about every imaginable degree, area of study and career path that can help you find the school that's right for you.

You are viewing lesson
Lesson
3 in chapter 5 of the course:

Back To Course

Introduction to JavaScript8 chapters | 39 lessons

- Computer Science 335: Mobile Forensics
- Electricity, Physics & Engineering Lesson Plans
- Teaching Economics Lesson Plans
- U.S. Politics & Civics Lesson Plans
- US History - Civil War: Lesson Plans & Resources
- HESI Admission Assessment Exam: Factors & Multiples
- HESI Admission Assessment Exam: Probability, Ratios & Proportions
- HESI Admission Assessment Exam: 3D Shapes
- HESI Admission Assessment Exam: Punctuation
- HESI Admission Assessment Exam: Linear Equations, Inequalities & Functions
- CPCE Prep Product Comparison
- CCXP Prep Product Comparison
- CNE Prep Product Comparison
- IAAP CAP Prep Product Comparison
- TACHS Prep Product Comparison
- Top 50 Blended Learning High Schools
- EPPP Prep Product Comparison

- History of Sparta
- Realistic vs Optimistic Thinking
- How Language Reflects Culture & Affects Meaning
- Logical Thinking & Reasoning Questions: Lesson for Kids
- Exceptions to the Octet Rule in Chemistry
- Database Hacking: Attack Types & Defenses
- Pride and Prejudice Discussion Questions
- Quiz & Worksheet - Frontalis Muscle
- Quiz & Worksheet - Dolphin Mating & Reproduction
- Octopus Diet: Quiz & Worksheet for Kids
- Quiz & Worksheet - Fezziwig in A Christmas Carol
- Flashcards - Measurement & Experimental Design
- Flashcards - Stars & Celestial Bodies
- Science Worksheets | Printable Science Worksheets for Teachers
- Classroom Management Strategies | Classroom Rules & Procedures

- Psychotherapy Approaches: Help & Review
- MEGA Early Childhood Education: Practice & Study Guide
- Foundations of Reading Test - NES for Wisconsin: Practice & Study Guide
- NYSTCE Communication & Quantitative Skills Test (080): Practice & Study Guide
- MTLE Mathematics: Practice & Study Guide
- MTEL Business: Planning Function of Management
- PARCC ELA - Grade 11: Delivering a Speech
- Quiz & Worksheet - Woodrow Wilson's Fourteen Points
- Quiz & Worksheet - Truman's Fair Deal & Post-WWII Economics
- Quiz & Worksheet - Veterinary Reception Areas
- Quiz & Worksheet - Anaconda Plan in the Civil War
- Quiz & Worksheet - Viral Zoonotic Infections

- Betrayal in Julius Caesar
- Tennis Terms & Safety
- Black History Month for Kids
- Soil Activities for Kids
- Average GMAT Scores & Percentiles
- Georgia Physical Science Standards
- Trail of Tears Lesson Plan
- Average GMAT Scores & Percentiles
- ACT English Tips
- Egg Drop Project Ideas
- TExES Music Exam Dates
- What is the ELM Test?

- Tech and Engineering - Videos
- Tech and Engineering - Quizzes
- Tech and Engineering - Questions & Answers

Browse by subject