How is the string behind computerChoice printed out?


I have a question regarding how this code is read, for my own understanding.

Never once is there a console.log to print out the computerChoice rock/paper/scissors answer at the very bottom of the code.. only the Math.random(); call is behind a print command. Is this inherent in the if/ else if/ else code blocks to print the string behind 'computerChoice = "___"'?

The way I understand it, the computer reads the code from the top down, so it compares the Math.random(); value to the conditions in the if/else if/else code, and I suppose there isn't a return because it's not within a function. But how does it know to call the new value of computerChoice again, and with the correct string from the blocks?

ps. Excuse the incorrect verbiage, I'm a super fresh beginner.

var userChoice = prompt("Do you choose rock, paper, or scissors?");

var computerChoice = Math.random();


if (computerChoice <= 0.33) {
    computerChoice = "rock";
else if (computerChoice <= 0.66) {
    computerChoice = "paper";
else {
    computerChoice = "scissors";


Once we check the random value in computerChoice we no longer need that variable. Rather than creating another variable we are able to re-use it to hold the corresponding string. There is no printing being done, only an assignment.


So the corresponding string is essentially replaced on top of it?


Yes. It overwrites the old value. JavaScript is loosely typed so a variable can be given new definitions of any type. This example overwrites a float with a string.


Thank you! I was scared to ask and you've helped me immensely. I appreciate it!


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.