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
- JavaScript – Sum of Digits of a NumberIn this article, we will learn how to find the sum of digits of a given number. The sum of digits can be… Read more: JavaScript – Sum of Digits of a Number
- JavaScript – Reverse a StringIn this article, we’ll look at three basic ways to reverse a string in JavaScript: the built-in reverse() method, a for loop, and the spread operator +… Read more: JavaScript – Reverse a String
- JavaScript – Find the Intersection of Two ArraysIn this article, we will explore how to implement a function in JavaScript to find the intersection (Common Elements) of two arrays. The… Read more: JavaScript – Find the Intersection of Two Arrays
- JavaScript – Convert an array to an objectThere are many ways to convert an array to an object in JavaScript. Let’s explore some of the common approaches – Using reduce()… Read more: JavaScript – Convert an array to an object
- JavaScript – Shuffle an array in a random orderTo shuffle an array in random order in JavaScript, you can use the sort() function with Math.random() or use the map() & sort()… Read more: JavaScript – Shuffle an array in a random order