JS20 / 15: Rock, Paper, Scissors, Lizard, Spock Game

This JavaScript lesson is about simple logic in the game of rock scissors paper, the main take outs for me were the use of the switch, instead of a if / else if / else statements, and the use of the indexOf() method to check the index at which an element is in the array.

Random Number / Choice

How to generate a random integer in a range between 0 and a given number. This was used to generate a number which after that is used to decide if the value is rock, scissors, paper.

  • Generate a random number between 0 and 1
    • | 0.25 / 0.45 / 0.85 / 0.999
  • multiply the random number by 3
    • | 0.75 / 1.35 / 2.55 / 2.997
  • Math.floor() rounds down the number
    • | 0 / 1 / 2 / 2

The above code returns the following lines after running it a couple of times. Using the returned value we can compare it with the user choice the define a winner.

randomInteger =  2  |  rpsChoice =  scissors
randomInteger =  0  |  rpsChoice =  rock
randomInteger =  1  |  rpsChoice =  paper
randomInteger =  0  |  rpsChoice =  rock
let rpsChoice = '';

  const randomInteger = Math.floor((Math.random() * 3))
  switch (randomInteger){
    case 0:
      rpsChoice = 'rock';
    case 1:
      rpsChoice = 'paper';
    case 2:
      rpsChoice = 'scissors';

  console.log('randomInteger = ', randomInteger, ' | ' , 'rpsChoice = ', rpsChoice);

More about the switch and Math.floor()

indexOf() Method

Returns the first index at which position is the element in the array,
If the element is not found it will return -1.

In the table result the indexOf() method find the strings in the array and returns the index of those strings 0, 2, 1 but in the case of the string ‘bike’ it returns -1 because is not in the array.

const vehicles = [ 'car', 'bus', 'plane'];
      ["vehicles.indexOf('car');", vehicles.indexOf('car')],
      ["vehicles.indexOf('plane');", vehicles.indexOf('plane')],
      ["vehicles.indexOf('bus');", vehicles.indexOf('bus')],
      ["vehicles.indexOf('bike')", vehicles.indexOf('bike')],

Array prototypes, index of


Other Topics in this lesson

At the end of the lesson there’s an explanation of how scripts are imported dynamically and the process of the Bundlers, like Webpack, are used to create an output. Tree Shaking is a part of this process where only one script, entry point, is loaded and the needed functions/modules from other scripts, leaving out the parts of a scripts that are not needed in the final application.

About Dynamic module import.

Course from Zero to Mastery


Posted in

0 responses


Your email address will not be published. Required fields are marked *