generate random number in javascript

To generate a random number in JavaScript, you can use the Math.random() method. This method returns a random floating-point number between 0 and 1. To generate random integers or non-decimal numbers, you can apply some additional math functions.

Here's an example of how to generate a random integer between a minimum and maximum value:

index.tsx
function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

// Example usage
console.log(getRandomInt(1, 10)); // Outputs a random integer between 1 and 10
193 chars
7 lines

And here's an example of how to generate a random floating-point number between a minimum and maximum value:

index.tsx
function getRandomFloat(min, max) {
  return Math.random() * (max - min) + min;
}

// Example usage
console.log(getRandomFloat(0.5, 1.5)); // Outputs a random floating-point number between 0.5 and 1.5
201 chars
7 lines

gistlibby LogSnag