(javascript) Rock, Paper, Scissors: stuck


hi everyone, total beginner here, I’ve started the web development 101 course a week ago and it’s been a lot of fun (like a weird puzzle game). But now I’m facing my first real “bump”, in the “rock paper scissors” assignment. For now, I’m just trying to have the computer choose between rock paper and scissors, and show the result in the console.

function computerPLay(){
let cpChoice = Math.random() * 3
if (cpChoice<=1) {
let cpHand = “rock”}
else if (cpChoice<=2) {
let cpHand = “paper”}
else {
let cpHand = “scissors”}
return cpHand

This makes perfect sense in my head, and yet it doesn’t work (cpHand is not defined). I feel like I missed something important, maybe in the lessons about JS functions, Could anyone point me to the right direction?


The issue you’re facing is that cpHand is not in scope when you try to return it. When you declare a variable using the let keyword, that variable is only available inside the current code block, which in your case would be the body of whichever if-statement ends up executing.

Let’s say cpChoice is 2 - Your code will execute the code block for scissors. In that code block, cpHand is declared, then assigned a value of “scissors”. Then, as execution leaves that code block (which is the scope of cpHand), it completely forgets what cpHand is.

There are a few ways to deal with this:

  1. Declare cpHand before your if-else-statements - That way, cpHand exists in a scope outside of those statements, and will be visible to your return statement.

  2. Use var declarations, instead of let declarations - These use function scope instead of block scope, so your variable will be visible in this case as well

  3. Don’t store the value in a variable at all - Just return it immediately

Hope you find that helpful!


Very helpful, thanks! It makes perfect sense, now.