JavaScript – Generate a random number or string

To generate random number in JavaScript, you can use Math.random() function. Let’s see how to use it to generate random number with an example :

function generateRandomNumber(min, max) { 
  // min and max included 
  return Math.floor(Math.random() * (max - min + 1) + min);
}

const randomNumber = generateRandomNumber(1, 6);
console.log(randomNumber); // 2

The following example will show how to generate a random string in JavaScript using Math.random() :

function generateRandomString(length) {
    let result = '';
    const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
    const charLength = characters.length;
    let counter = 0;
    while (counter < length) {
      result += characters.charAt(Math.floor(Math.random() * charLength));
      counter += 1;
    }
    return result;
}

console.log(generateRandomString(5)); // ItO5t

Similar Reads