Chance.js Random Data Generator

1.1.13 · active · verified Sun Apr 19

Chance.js is a comprehensive utility library designed for generating a wide variety of random data in JavaScript environments, including Node.js and browsers. It currently stands at stable version 1.1.13 and has a generally infrequent release cadence, with major updates occurring as needed for new features or critical bug fixes rather than on a fixed schedule. Its core differentiator is its foundation on the Mersenne Twister algorithm, which allows for repeatable pseudo-random sequences when seeded, making it invaluable for testing, data simulation, and reproducible scenarios. The library provides generators for basic types like numbers, characters, and strings, as well as complex data such as names, addresses, dice rolls, and geographical coordinates, distinguishing itself by its breadth and optional determinism.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to instantiate Chance, generate various types of random data, and critically, how to use seeding to achieve reproducible random sequences for testing or deterministic data generation.

import Chance from 'chance';

// Create a new Chance instance (can be seeded for repeatable results)
const chance = new Chance(process.env.RANDOM_SEED ?? undefined);

console.log('Generating some random data:');
console.log(`- Random Name: ${chance.name()}`);
console.log(`- Random Age: ${chance.age()}`);
console.log(`- Random GUID: ${chance.guid()}`);
console.log(`- Random Sentence: ${chance.sentence()}`);
console.log(`- Random Email: ${chance.email()}`);
console.log(`- Random IPv4 Address: ${chance.ip()}`);
console.log(`- Random Dice Roll (d6): ${chance.d6()}`);
console.log(`- Random Boolean: ${chance.bool()}`);
console.log(`- Random Color (hex): ${chance.color({ format: 'hex' })}`);
console.log(`- Pick a random element: ${chance.pickone(['apple', 'banana', 'cherry'])}`);

// Demonstrating seeding for reproducibility
const repeatableChance = new Chance('my-seed-value');
const firstString = repeatableChance.string();
const secondString = repeatableChance.string();

const anotherRepeatableChance = new Chance('my-seed-value');
const thirdString = anotherRepeatableChance.string();

console.log('\nDemonstrating reproducibility with seeding:');
console.log(`- First string with seed: ${firstString}`);
console.log(`- Second string with seed: ${secondString}`);
console.log(`- Third string with same seed (should match first): ${thirdString}`);
console.log(`- Are first and third strings identical? ${firstString === thirdString}`);

view raw JSON →