Guess The Number

Discover variables and inputs with this JavaScript Blocks activity!

  • Get started
  • JavaScript Blocks
  • Inputs
  • Variables
  • Random
Print lesson
  • Leeftijd 8+
  • 30 min
  • JavaScript Blocks


Second project using the JavaScript Blocks editor and introduces the students to the use of variables, user inputs and random numbers. When the button is pressed a random number between a given range is shown.

Teacher Guide



5 steps

Step One

In the JavaScript Blocks editor select the Input option from the block menu and find the “On button press” block and drag onto the workspace.

Once on the workspace the button variable can be changed to either “A”, “B” or “A+B”. In this case select “A”. Code that is then placed inside this input will only happen when the button is pressed.

Step Two

From the block menu select the “Variable” and click “Make a Variable”. A variable is where data can be stored.

A popup dialogue box will then ask you to name your variable. In this example name it “X”

Step Three

Still in the Variables option in the block menu select the “Set item to 0” block. This will enable a variable to be set to a given value.

Move the “Set variable to” block inside the “On button” block. Now when the button “A” is pressed the variable “item” will be set to 0.

The variable name can be changed by selecting the down arrow next to the word item and changed to a different variable. As we have created a “X” variable, select this.

Step Four

The next element is to build a random number element within the program. From the block menu select the “Math” option and select “pick random 0 to 4”

We would like to set the variable “X” to be a random number, so drag the random number block and replace the “0” with the random block.

As we would like the random number to be in the range from 0 to 9, click the “4” and replace it with “9”.

Step Five

The next stage is to show the random number on the LEDs. From the Basic option in the block menu select show number and drag onto the workspace.

Move the “Show number” block below the “set X” block. This will now show the number 0 if the program was run.

To show the random number we need to set the show number block to the variable “X”. From the Variable option in the block menu select the “X” variable block and drag onto the workspace.

Move the “X” variable block into the show number.

Save the project and download to the micro:bit.


Try to add the following functionality:

  • Clearing the screen on a “B” button pressed
  • Add an animation of randomly picking a number
  • Develop the animation so it slows down to the selected random number

Learn More

Check out the 'Temperature' lesson to learn about using the device's sensors as an input device.

Selecting this opens external content from our support system, which adheres to their privacy policy.