1Math.random()
2// will return a number between 0 and 1, you can then time it up to get larger numbers.
3//When using bigger numbers remember to use Math.floor if you want it to be a integer
4Math.floor(Math.random() * 10) // Will return a integer between 0 and 9
5Math.floor(Math.random() * 11) // Will return a integer between 0 and 10
6
7// You can make functions aswell
8function randomNum(min, max) {
9 return Math.floor(Math.random() * (max - min)) + min; // You can remove the Math.floor if you don't want it to be an integer
10}
1function getRandomNumberBetween(min,max){
2 return Math.floor(Math.random()*(max-min+1)+min);
3}
4
5//usage example: getRandomNumberBetween(20,400);
6
1var random;
2var max = 8
3function findRandom() {
4 random = Math.floor(Math.random() * max) //Finds number between 0 - max
5 console.log(random)
6}
7findRandom()
1function randomNumber(min, max) {
2 return Math.floor(Math.random() * (max - min)) + min + 1;
3}
1/*
2 The Math.random() function returns a floating-point, pseudo-random
3 number in the range 0 to less than 1 (inclusive of 0, but not 1)
4 with approximately uniform distribution over that range — which you
5 can then scale to your desired range. The implementation selects the
6 initial seed to the random number generation algorithm; it cannot
7 be chosen or reset by the user.
8*/
9function getRandomInt(max) {
10 return Math.floor(Math.random() * Math.floor(max));
11}
12
13console.log(getRandomInt(3));
14// expected output: 0, 1 or 2
15
16console.log(getRandomInt(1));
17// expected output: 0
18
19console.log(Math.random());
20// expected output: a number from 0 to <1