Random number in JavaScript for Beginners - Main image

Intermediate

Random number in JavaScript for Beginners

Using a fun and useful example, we are going to show you how to generate a random number in JavaScript.

Miha Cirman
8 min read

In this blog post, you will get to know everything you need to make your first random number app in JavaScript. I know this is a blog about how to make a random number in JavaScript (check out our blog post on what is JavaScript), but I need to tell you our office story first. :D

 

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.

Steps:

  • Create an HTML
  • Create a JavaScript
  • Connect the JS file with the HTML file
  • Test the app

Let’s start the fight!

 

Learn HTML, CSS and JavaScript with our web dvelopmetn course - for beginners, where we build a modern WEB site from scratch.

Start Now

 

A web page to show 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.

 

Random number in JavaScript - writing the code

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, meaning 0.345, 0.87695, 0.1, 0, 0.11111,....  I hope you get the picture.

Random number in JavaScript

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

 

Learn HTML, CSS and JavaScript with our web dvelopmetn course - for beginners, where we build a modern WEB site from scratch.

Start Now

 

JavaScript code to choose players

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.

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.

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.

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.

 

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...

 

 

 

Loading FB comments...