DEV Community

Cover image for Random Seed in JavaScript and Node.js
Gabe Romualdo
Gabe Romualdo

Posted on • Edited on • Originally published at xtrp.io

14 4

Random Seed in JavaScript and Node.js

Introduction

Random seed is a method of initializing random number generators using an initial seed value. Random generators with the same seed will output the same pseudo-random results.

I found this method to be particularly useful when developing a game I'm working on, which has a random 'Daily Challenge'. In this case, random seed can be useful to select a random game using the current date as a seed.

Code

So, here's how to create a random seed in Node.js, using the seedrandom NPM package:

// In Node.js
const seedrandom = require('seedrandom');
const generator = seedrandom('[your seed here]');
const randomNumber = generator();
Enter fullscreen mode Exit fullscreen mode

And if you're on the client-side:

// On The Browser
const generator = new Math.seedrandom('[your seed here]');
const randomNumber = generator();
Enter fullscreen mode Exit fullscreen mode

In both of these code snippets, the generator function will return a new random number each time, given the seed the generator was initialized with. In this case, it will be formatted as a numerical value, although

Dependencies

If you're running on Node.js, download the seedrandom package as follows:

npm install seedrandom
Enter fullscreen mode Exit fullscreen mode

Or using Yarn:

yarn add seedrandom
Enter fullscreen mode Exit fullscreen mode

If you're writing client-side code without webpack, you can either download the file from seedrandom's GitHub repository, or use a CDN by adding the following code snippet at the end of your <body> tag:

<script src="https://cdnjs.cloudflare.com/ajax/libs/seedrandom/3.0.5/seedrandom.min.js"></script>
Enter fullscreen mode Exit fullscreen mode

Conclusion

Random seed is one of a few features that is present in most major programming languages but is not available out-of-the-box in JavaScript. It can be incredibly useful in a wide array of cases, both on the web and running on the server-side using Node.

I hope this helps, and thanks for scrolling.

— Gabriel Romualdo, March 26, 2021

Postgres on Neon - Get the Free Plan

No credit card required. The database you love, on a serverless platform designed to help you build faster.

Get Postgres on Neon

Top comments (2)

Collapse
 
aszxqaz profile image
aszxqaz

It was helpful!

Collapse
 
devkaahl profile image
Muhammad Khalil

This is beautiful

Heroku

This site is powered by Heroku

Heroku was created by developers, for developers. Get started today and find out why Heroku has been the platform of choice for brands like DEV for over a decade.

Sign Up

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay