create a random generator in javascript

To create a random generator in JavaScript, you can use the built-in Math object which provides random methods. There are several ways to generate random numbers in JavaScript.

  1. Math.random() method:

The Math.random() method returns a random floating-point number between 0 (inclusive) and 1 (exclusive).

index.tsx
function getRandom() {
  return Math.random();
}
getRandom(); // returns a random number between 0 and 1
105 chars
5 lines
  1. Math.floor() method:

The Math.floor() method rounds down a number to the nearest integer.

index.tsx
function getRandomInt(max) {
  return Math.floor(Math.random() * Math.floor(max));
}
getRandomInt(10); // returns a random integer between 0 and 9
147 chars
5 lines
  1. Random string generator:
index.tsx
function randomString(length) {
  let result = '';
  let characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  let charactersLength = characters.length;
  for (let i = 0; i < length; i++) {
    result += characters.charAt(Math.floor(Math.random() * charactersLength));
  }
  return result;
}

randomString(5); // returns a random string of length 5
376 chars
12 lines

There are also libraries like Chance.js and Faker.js which can be used to generate random data.

related categories

gistlibby LogSnag