Random number in JavaScript - Practical example - Main image

Intermediate

Random number in JavaScript - Practical example

Take a look at how to generate a random number in JavaScript. Using a practical example, we are going to show you how you can use this very useful function.

Miha Cirman - CodeBrainer
Miha Cirman
11 min read

Random number in JavaScript is important because a lot of applications need to offer users a seemingly random choice, like a shuffle for your best album songs. If you want to show a random color to your user, you would use a random number generator as well.

In this blog post, you will get to know everything you need to make your first random number app in JavaScript. If you are new to JavaScript you can also check our blog post on what is JavaScript.

Learn how to make a random number in JavaScript:

  • Using Math.random()
  • How to choose numbers up to a given number (e.g. up to 100)
  • A way to randomly generate two numbers in a range (e.g. 32-50)
  • How to improve randomness with Crypto.getRandomValues()

We are strong believers in practical examples (test your Web development knowledge) and there is a funny story how this blog post was born.This is a great example as it shows a random number generator and a way you can show values on a website in a more colorful way with images, and texts.

 

Random number in JavaScript - writing the code

Using Math.random() function

We will use the Math.random() function, which will give us a random number in JavaScript. This function will give us a number from 0 to 1, for example 0.345, 0.87695, 0.1, 0, 0.11111,....

 

How to choose an integer up to a given number

So what do we do if we want to choose a random number from 1 to 10? For that, we will use a bit of math. The first thing we need is to make a number bigger by multiplying the random number by 10. Unfortunately, this would still give us decimal numbers, and we need integers. We will use Math.floor for that. This will provide us with the first integer, that is smaller than our number. So we have integers, but there is another trick.

We need to increase the multiplicator by one to get 10 as well. So the code will look like this:Using Math floor
We can make a function for that:

JavaScript
Choose an integer up to a given number - JavaScript - CodeBrainer

Thanks for reading!

If you like our code, you can give back by sharing this article!

 

A way to randomly generate two numbers in a range

A lot of times you will need to create a random number in JavaScript within a given range. In fact, let’s say you need to randomly calculate a basketball result, you know that score will be between 70 and 130 (for example ;)). So how do you generate numbers from a range.

The function below will give you a random number (float) within a range:

JavaScript
Random number within a range - JavaScript - CodeBrainer

Thanks for reading!

If you like our code, you can give back by sharing this article!

This function returns a float in a given range (greater or equal to the min, but less then maximum

The function below returns a random integer within a range:

JavaScript
Random integer within a range - JavaScript - CodeBrainer

Thanks for reading!

If you like our code, you can give back by sharing this article!

 

The story about why we need to generate a random number in JavaScript

Once in a while, you have to have some fun to be able to work in a creative environment. Here at CodeBrainer, we like to play retro games to get our blood flowing. We are currently using a console some of you may not even have heard of, and that console is Playstation 2. Yes we know, there are a lot of newer consoles out there. Since its release back in 1992, Mortal Kombat has been one of my favourite video games of all time. Considering its last update was in 2019, it is here to stay, at least for us :D

Playing games not only relaxes us but also, the loser has to make the next coffee. We have a quick tournament of Mortal Kombat to decide for us. I must admit that I do make a lot of coffee these days. I wonder, was I tricked into playing this with professionals. But I love it. 

There is also a problem playing retro gaming consoles; we only have three characters (no time to play all the levels and win new ones) and two old controllers. One works very well the other is a little bit crooked. So we have to choose a character and a controller for each player

We are teaching software development so I thought that we could build a kind of wheel of fortune that will choose this for us. Since we have a JavaScript course, I decided to build one in JavaScript.

 

Making a practical example for random choices in JavaScript

Steps to make our practical example for randomizer in JavaScript:

  • Create an HTML (to show results) (What is HTML?)
    • Create UI for user
  • Create a JavaScript file
  • Connect the JS file with the HTML file
  • Write the code in JS
    • Add arrays and objects to show results
    • Make a random generator
    • Show choice on the screen (Using DOM)
  • Test the app

 

Let’s start the fight!

Start our mentor-led course, where our mentor leads you on every step of the way. Claim your FREE trial today.

Free trial

A website to show randomly chosen players

We will show you how to make a simple web page using just a few tags. All the tags are listed in our top 10 HTML tags list. It will be enough to have all the features we need for a successful day at the office. Meaning we will have a process on deciding who will make the next coffee. Here at CodeBrianer we take this process pretty serious so don’t judge us :D

Let’s start with a funny title. We will put the title in the h1 tag.

Funny title

Simple. Chose a good title for your version. If you play with our Plunker, you can change it and see the result straight away (the link to the whole code is a the bottom of this blog post).

Next we will display the list of players. We will put the list in a separate paragraph (<p></p>). The list will be unordered so use the <ul></ul> tags, and each item will be written in <li></li> tags.

The list of players will look something like this:

First paragraph

We will also add two more lists, one for controllers and the other one for the characters you can play.

The list for controllers will look something like this:

Second paragraph

And for characters:

Third paragraph

 

 

Linking HTML and JavaScript

I will show you the most straightforward way of linking HTML and JavaScript. For that, we will use a button that will call a function on click. The function will be named choosePair(), which will execute on click.

Button code

The text inside the button tag is the text you will see displayed on the button.

Having a button is the first step into linking HTML and JavaScript. The next step is having a way of showing the result on the screen. For that, we prepared a paragraph with an id. Id is an important part since with id we can then find the element in javascript.

Id element

Just a quick look at how this will look in JavaScript:

Element in JavaScript

When you have an element, you can change its value. But we will show that in the next part.

 

Start our mentor-led course, where our mentor leads you on every step of the way. Claim your FREE trial today.

Free trial

JavaScript code for our player randomizer

JavaScript code for choosing players

Let me describe the code a little bit. The winner variable is a connection to the HTML element. We will change the content of it at the end of the function.

The next variable is “players” (an array) it has all the names of the players you want. If you want you can add more players. It will work fine with our script. The controllers variable is similar to the players, but it stores the list of controllers to play with, for now, we only have two.

A more advanced example is characters, where we have a list of characters. Each character has a name and image. The image is a URL address to the image, I have found images on Wikipedia and just extracted the URLs for them.

 

The code to choose player and controllers

Let me describe the code, that will choose a player for us:

Choosing a single player

Player1 and player2 are variables that will store the index for the name of a player. We get the index using the random() function. As we have shown before we need to multiply random() with the number of the last value. But this time we do not have to add 1, because an array is zero-based. So the index for the last element will be 1 in our case with two elements.

We have added “while loop” as well (the “while loop” runs a block of code as long as a condition is true). Our loop will run until both indexes are the same as we don’t want a result where Player 1 would compete against himself/herself. To learn more about loops read our article on how to use loops in JavaScript.

The procedure for characters is the same, but I have cheated a little bit for controllers since I know there are only two controllers.

Choosing a controller

For controller2 I calculate the opposite controller in this case math comes in handy, and for binary, we get the other case by subtracting the value from 1.

 

Showing results on screen

Now we just need to show the result on screen.

JavaScript code to show result

You can see that we have combined the string with HTML tags and values of our variables. We set the HTML to the winner paragraph with an innerHTML property.

There are a few points I have to make. We used a CSS class (inside style.css) for div (this is a tag that will group the details of a player). The class is called inline, and it will have the property “display:inline-block”, this is an important part since we want to show the players side by side.

CSS class

But since we have a CSS class, we can add a little bit of style, and for example, add spacing (margin-right) and make the VS sign appear in the middle.

We will read the values for a player using:

Player 1

The same goes for the controller. For the character, we will use a property of an object. So we will read the image like this.

Characters

That is it, check the final result and code and do it yourself.

 

How to make a random number more random in JavaScript

Problem with Math.random() is that is not that random. Numbers tend to repeat in similar conditions (e.g. starting web site again). Sometimes having a real random number is very important, especially with cryptography where randomness also makes cryptography more secure.

For most programmers better random number is more about having a spread choices across the designed range, and there is a simple fix for that, called Crypto.getRandomValues(). You still need a bit of work to use but here is the function that replaces Math.random(). Function also has a fallback if Crypto API is not present within the browser.

JavaScript
Random number cryptography - JavaScript - CodeBrainer

Thanks for reading!

If you like our code, you can give back by sharing this article!

All you need is to replace Math.random() with betterMathRandom in all the functions.

Still for true cryptographic functions it is vise to go even deeper when creating random numbers.

 

Final result

Below you can take a look at the final result of our simple but effective way of using a random number in JavaScript. It gets things done. :D

Final result

 

The final code

Here you can copy the code or just take a look at our code. 

Let us know if you have any improvements or if you need any help. 

Time for “coffee”, let’s play! At least today I play with Liu Kang...