Notes

JavaScript - Generate random values

author: Paul Kim

categories: js, nodejs

tags: js, nodejs

JavaScript - Generate random values

Math.random() returns a pseudo-random number between 0 (inclusive) and 1 (exclusive).

// generate random floating-point between low (inclusive) and high (exclusive)
function random(low, high) {
  return Math.random() * (high - low) + low
}

// generate random integer between low (inclusive) and high (exclusive)
function randomInt(low, high) {
  return Math.floor(Math.random() * (high - low) + low)
}

// generate random integer between low (inclusive) and high (inclusive)
function randomIntInc(low, high) {
  return Math.floor(Math.random() * (high - low + 1) + low)
}

Generate universally unique identifiers (UUID)

npm install uuid
const uuidv4 = require('uuid/v4')

var uuid1 = uuidv4() // e.g. 32a4fbed-676d-47f9-a321-cb2f267e2918
var uuid2 = uuidv4() // e.g. 8b68cf5b-d619-4281-b560-1578b0ee891d
Source

Random values in JavaScript and Node.js


ChromeEdgeFirefoxOpera

© 2021 paulkode.com. All rights reserved.