Menu Close

JavaScript Random

In this JavaScript tutorial, you are going to learn about JavaScript random. In the previous tutorial, we have seen all about JavaScript Math with the help of the example. To generate random numbers in JavaScript we will use the Math.random() function.

To understand this example, You should have basic knowledge of JavaScript programming.

Table of Contents

JavaScript Random

Math.random() function return the random floating-point number from 0 ( inclusive ) and 1 ( exclusive).

Example: Generate Random number


// generate random number
let value = Math.random();
console.log(value);

Note: Math.random() always return a number lower than 1.

In above example, we have declared a variable value and assign random number to it.

JavaScript Random Integer

To return random number from 0 to 9,use Math.floor() and Math.random() functions.

Example: Return random number from 0 to 9


// return a random integer.
let x = Math.random() * 10;
// Math.floor(x) return the largest integer not greater than x.
console.log(Math.floor(x)); 

Example: Return random number from 0 to 10


// return a random integer.
let x = Math.random() * 11;
// Math.floor(x) return the largest integer not greater than x.
console.log(Math.floor(x)); 

Example: Return random number from 0 to 99


// return a random integer.
let x = Math.random() * 100;
// Math.floor(x) return the largest integer not greater than x.
console.log(Math.floor(x));

Example: Return random number from 0 to 100


// return a random integer.
let x = Math.random() * 100 + 1;
// Math.floor(x) return the largest integer not greater than x.
console.log(Math.floor(x)); 

Example: Return random number from 1 to 10


// return a random integer.
let x = Math.random() * 10;
// Math.floor(x) return the largest integer not greater than x.
console.log(Math.floor(x) + 1);

Example: Return random number from 1 to 100


// return a random integer.
let x = Math.random() * 100;
// Math.floor(x) return the largest integer not greater than x.
console.log(Math.floor(x) + 1);

Summary

In this guide, we have demonstrated to you, How to generate random number In JavaScript with the help of the example

Here we generated the random integer using JavaScript Math.floor() function, You can use Math.ceil() as well. I recommend you, If you want to work with a random number, please check out our JavaScript Math tutorial.

Previous Article
Next Article

Was this post helpful?

Related Posts