How is the string behind computerChoice printed out?


#1

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.


https://www.codecademy.com/courses/javascript-beginner-en-Bthev-mskY8/0/4?curriculum_id=506324b3a7dffd00020bf661#


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

var computerChoice = Math.random();

console.log(computerChoice);

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


#2

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.


#3

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


#4

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.


#5

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


#6

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