Chance.js Random Data Generator
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
-
TypeError: Chance is not a constructor
cause Attempting to call `Chance()` directly without the `new` keyword.fixUse `const chance = new Chance();` to instantiate the Chance generator. -
ReferenceError: Chance is not defined
cause The Chance library was not imported or included correctly, or you are trying to use a CommonJS `require` in an ES Module context without proper setup, or vice versa.fixEnsure you have `import Chance from 'chance';` (ESM) or `const Chance = require('chance');` (CJS) at the top of your file, or that the `<script>` tag is loaded in a browser environment. -
ReferenceError: require is not defined
cause Trying to use `require('chance')` in an ES Module context (e.g., in a file where `type: 'module'` is set in `package.json` or a `.mjs` file).fixChange the import to `import Chance from 'chance';`. If you truly need CommonJS, ensure your file is treated as CJS (e.g., using `.cjs` extension or `type: 'commonjs'` in `package.json`).
Warnings
- gotcha When using Chance.js, always instantiate it with `new Chance()` to get a generator instance. Calling `Chance()` directly without `new` will result in a TypeError because it's a constructor.
- gotcha To ensure true randomness or unique sequences across different runs in a production environment, avoid hardcoding a seed or remove seeding entirely. Seeding is primarily for reproducible testing.
- gotcha While Chance.js supports both CommonJS and ESM, mixing import styles (e.g., `require` in an ESM module or `import` in a CJS module without proper transpilation) can lead to module resolution errors. Ensure your project's module system is consistently configured.
Install
-
npm install chance -
yarn add chance -
pnpm add chance
Imports
- Chance
import { Chance } from 'chance'; import chance from 'chance';import Chance from 'chance';
- Chance
import Chance from 'chance';
const Chance = require('chance'); - Chance (global)
import Chance from 'chance'; // In browser without build step
<script src="path/to/chance.min.js"></script> // Chance is now available globally
Quickstart
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}`);