Project Rock, Paper, Scissors: nested if

Can we consider the first if statement and the nested if as “if first ‘if’ is scissors while the nested “if” is rock, then…”

if (userChoice === 'scissors'){
  if (computerChoice === 'rock'){
    return 'Computer won';
  }   else {
    return 'The user won';
  }

  }

A link to the lesson: https://www.codecademy.com/courses/introduction-to-javascript/projects/rock-paper-scissors-javascript

You could do this

if (userChoice === 'scissors' && computerChoice === 'rock') {
    return 'Computer won';
}
else {
    return 'The user won';
}

I don’t think that’s quite the same thing. In nastya_nmk’s code, the else is connected to the nested if. In your example, it’s connected to the only if there is.

So, in nastya_nmk’s code, if the userChoice was ‘rock’, nothing would happen. In your code, it would return ‘The user won’.

Here is the same thing in Python and it returns computer won

user = "scissors"
computer = "rock"

if user == "scissors" and computer == "rock":
    print("Computer won")
else:
    print("User won")

I said userChoice is rock, not computerChoice. :slight_smile:

1 Like

Welcome back to the forums! :slight_smile:

Pretty much, yes; though I’d have used “and” rather than “while”.

Your code evaluates the first if. Should that be true, then it evaluates the second if. Should that also be true, you return that the CPU won; if false, that the player won.

Your nested ifs are, I think doing the equivalent of:

if (userChoice === 'scissors' && computerChoice === 'rock') {
    return 'Computer won';
} else if (userChoice === 'scissors') {
    return 'User won';
} else {
    // do nothing...
}

I think you understand how the nested ifs are working, but I would ask whether they’re correctly evaluating (in this form) the outcome of the game? :slight_smile:

1 Like

Thank you. The following works too:

But I do not fully understand why we need the line with “else if (userChoice === ‘scissors’)” . If I do not include it, I receive an error.