How to Create a JavaScript Random Boolean Function (NodeJS, Browser)

This article covers how to create a function to generate random boolean (true and false or 1 and 0) values using JavaScript. It also contains an example of how to test and visualize the results using the command line or the browser.
The code covers how to create a function that returns a boolean value around 50% of the time. If you are working on a simulation or generative art where you need better control over the percentage, I’ll include a link to an article on a weighted boolean function at the end of this article.
Step 1. Create a project
- Create a project:
$ mkdir -p ~/projects $ cd ~/projects $ mkdir js-coinflip-101 $ cd js-coinflip-101
Step 2. Initialize the project as a module
- Create a package.json file by initializing the project with npm:
$ npm init -y
- Open the project in a code editor
- Add this line to package.json after the description and save the file:
"type": "module",
Step 3. Create a JavaScript file
Use the editor to create a new file called coinflip.js or on the Mac command line:
$ touch coinflip.js
Step 4. Create the coinFlip function
Edit coinflip.js, add the following and save the file:
The code does the following:
- Exports a coinFlip function that returns either a 1 or a 0
- Math.random() returns a random number between 0.0 and 1.0
- Math.round() returns 0 if the random number is less than 0.5 or 1 if it is greater than or equal to 0.5
- The 1 and 0 in JavaScript can be interpreted as true (1) or false (0)
Step 5. Add a test file
- Create a new file called test-coinflip.js
- Paste in this code and save the file:
The code does the following:
- imports the coinFlip function
- defines a function to test the coinFlip function
- defines a constant limit for generating an array of coin flip results
- logs the array of coin flip results
- uses the JavaScript reduce method to count the occurrences of 1s and 0s in the array
- logs the summary of the occurrences
- calls the test function
Step 6. Run the test function
To run the test function, do the following from the projects folder on the command line:
$ node test-coinflip.js
You should see a result similar to this:
[
1, 1, 1, 0, 1, 0, 1, 1, 0, 0, 1, 1,
0, 1, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0,
1, 1, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1,
1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1,
1, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0,
1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1,
1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0,
0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1,
0, 1, 0, 0
]
{ '0': 49, '1': 51 }
- All but the last line is the array of results
- The last line is the summary of the occurrences
- If you run it several times the summary may never show an exact 50 / 50 split
- Sometimes you may even see close to a 30 / 70 split
- But most runs result in no more than a 40 / 60 split
Step 7. Run the test in a browser
Now I am going to show you how to draw a 10 x 10 grid, using an HTML canvas element, to visualize the distribution of the random flips generated by the coinFlip function.
- Create a file called index.html in the root of your project
- Paste in this code and save it:
The code does the following:
- defines a header section
- defines a title to appear in the browser tab
- loads a stylesheet (app.css) that will need to be created
- defines a body section
- defines canvas element where we will draw a grid to visualize a series of calls to the coinFlip function
- loads a script module (app.js) that will need to be created
Step 8. Create a stylesheet
To center the canvas on the screen I am going to show you how to use the stylesheet referenced by the HTML file above.
- In the root of the project create a file called app.css
- Paste in the code below and save the file:
The code does the following:
- centers the canvas element in the middle of the screen
Step 9. Create the app file
To draw the grid I am going to show you how to define the app file loaded by the HTML file above.
- In the root of the project create a file called app.js
- Paste in the code below and save the file:
The code does the following:
- gets a handle to the canvas element in the HTML
- defines a series of constants
- to simplify the code a square will be drawn where width and height are the same constants
- SCREEN_SIZE is the width and height of the canvas element (it should match the canvas width and height attributes)
- DIM is the row and columns of the grid to represent each call to coinFlip which will be show in a grid “cell”
- CELL_SIZE calculates the size of a cell to draw on the screen by dividing the screen size by the number of rows or columns
- BORDER is the border size to leave empty around each cell
- NEON_GREEN is an HTML constant for a neon color to fill each true / 1 cell with
- an array of random coinFlips is filled with results
- the length of the array is DIM * DIM to match the number of results to fill a DIM * DIM grid (10 x 10 cells = 100 results needed)
- the arr (array value) is logged to the console which you can view in the browser via the debugger / inspector console window
- a context handle to the canvas object is created for drawing
- the context is cleared and replaced with a colored background
- a cursor for looping through the array is created
- inner and outer loops for converting the array to a grid are defined
- if a result in the array was a 1 a neon green cell is drawn, otherwise it is black
- adjustments are made to draw the cell slightly smaller so it appears to have a border around it
Step 10. Test the project in the Chrome browser
You have to run the code through a local Web server.
- On a Mac you can serve the files from the current folder using this command:
python -m SimpleHTTPServer $PORT || 8000
- Leave that command running
- Open up the Chrome browser and browse to:
http://localhost:8000/
To see different results, reload the browser window.
Source Code
Conclusion
In this article you learned how to:
- generate a function that returns a random boolean result
- write a another function to test how evenly distributed the results were
- use the canvas object in a browser to visualize the distribution
Related Articles
- How to Create a JavaScript Module (NodeJS, Browser)
- How to Select a JavaScript Random Array Item (NodeJS, Browser)
- How to Create a JavaScript Weighted Random Function (NodeJS, Browser)
References
- Math.random() – [1]