links: [[JS MOC]] --- # Random life, A guide on how to use random Javascript has a built in method to generate a random number. It generates a random value between 0 (inclusive) to 1 (exclusive) ```js let randomVal = Math.random() ``` ## Generate random number between two values The function below generates a random value with min inclusive and max exclusive ```js function getRandomArbitrary(min, max) { return (Math.random() * (max - min)) + min } ``` In order to generate random value inclusive of max we need to add 1 ```js function getRandomArbitrary(min, max) { return (Math.random() * (max - min + 1)) + min } ``` ## Generate unique random number Consider a situation where you want to get random element with unique index from an array. Which means if there are 4 elements and you have to generate random index every time without repeats like (2, 3, 0, 1) ```js export const generateRandomIndexArray = arrayLength => { const originalIndices = [...new Array(arrayLength).keys()]; let indices = [...originalIndices]; return { getRandomIndex: () => { if (indices.length === 0) { indices = [...originalIndices]; } const randomIndex = Math.floor(Math.random() * indices.length); const randomIndexVal = indices.splice(randomIndex, 1); return randomIndexVal[0]; }, }; }; ``` ## You can use random with a percent chance Consider you have 100 users and you want to give bonus gift randomly to 10% of the users you can do something like this ```js const random = Math.random() // 10% of chance to get value less than 0.1 if(random < 0.1) { // give user a bonus } ``` --- tags: #math, #random sources: - [MDN random](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random) - [Generate unique randoms](https://waimin.me/Generate_unique_randoms/)