Please anybody tell me the code to generate the random number in javascript.

Dani AI

Generated

As already pointed out, the usual starting point in JavaScript is the built-in pseudo-random generator. The examples below show common, practical patterns that were missing from the thread, plus important cautions that implicitly touched on by noting other languages have similar functions.

Math.random returns a floating-point number in the range 0 (inclusive) to 1 (exclusive) (MDN Math.random). For basic uses:

Math.random(); // returns a number >= 0 and < 1

To get integers without introducing bias, map the float into the desired range with Math.floor:

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

function randomIntExclusive(min, maxExclusive) {
  return Math.floor(Math.random() * (maxExclusive - min)) + min;
}

const randomElement = arr[Math.floor(Math.random() * arr.length)];

Caveats and secure alternatives: Math.random is not cryptographically secure. For security-sensitive needs, use the Web Crypto API and rejection sampling to avoid modulo bias (MDN getRandomValues):

function secureRandomInt(min, max) {
  const range = max - min + 1;
  if (range <= 0) throw new Error('max must be >= min');
  const cryptoObj = (typeof crypto !== 'undefined') ? crypto : null;
  if (!cryptoObj || !cryptoObj.getRandomValues) throw new Error('crypto.getRandomValues not available');

  const maxUint32 = 0x100000000; // 2^32
  const limit = maxUint32 - (maxUint32 % range);
  const array = new Uint32Array(1);
  let rnd;
  do {
    cryptoObj.getRandomValues(array);
    rnd = array[0];
  } while (rnd >= limit);
  return min + (rnd % range);
}

Troubleshooting notes: avoid Math.round for ranges (it biases ends); avoid naive modulus on low-entropy sources; Math.random cannot be seeded by the spec—use a seeded PRNG library when deterministic sequences are required.

Recommended Answers

All 2 Replies

Using the (esp the random() function) along with tutorial should get you going.

ya sos,

almost all scripting and programming language have random function

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.