Sometimes you want to pick some random number or array in JavaScript. In this tutorial, I'll show you how.


Picking a random number

1. Create a variable with any name.

var random = "Hi";

2. Pick a random number using Math.random().

var random = Math.floor(Math.random() * 101);

The above code will pick a random number from 0 - 100

3. Log the result in console.

console.log(random);
Final code:

var random = Math.floor(Math.random() * 101);
console.log(random);


Picking random array from variable

1. Create a variable with any name, and put your arrays in it.

var whoiscool = ["Minecraft", "NiceSapien", "Both"];

2. Create a variable for picking random array and use Math.random() in it.


var random = Math.floor(Math.random() * whoiscool.length);

3. Log the results in console

console.log(whoiscool[random]);

Output will be random, mine was:



Final code:

var whoiscool = ["Minecraft", "NiceSapien", "Both"];
var random = Math.floor(Math.random() * whoiscool.length);
console.log(whoiscool[random]);


Making It faster

~~  is much faster than Math.floor. So you can use it instead.

var random = ~~(Math.random() * whoiscool.length);