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
Codigo
let rpsChoice = '';
const randomInteger = Math.floor((Math.random() * 3))
console.log(Math.random())
switch (randomInteger){
case 0:
rpsChoice = 'rock';
break;
case 1:
rpsChoice = 'paper';
break;
case 2:
rpsChoice = 'scissors';
break;
default:
break;
}
console.log('randomInteger = ', randomInteger, ' | ' , 'rpsChoice = ', rpsChoice);
More about the switch and Math.floor()
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/floor
https://www.w3schools.com/js/js_switch.asp
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.
Código
const vehicles = [ 'car', 'bus', 'plane'];
console.table([
["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
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf
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.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules#dynamic_module_loading
Course from Zero to Mastery
Reply