Javascript switch statement nested inside If statement cannot access other variables and returns Unidentified

I am working on a Rock/Paper/Scissors game like as usual. Somehow my if and switch statements cannot read the values set by the other two functions and when I console.log result it returns undefined

However when I manually set user and computer variables decideWinner function works as intended.

I’ve been tinkering with it for a couple of hours and some help would be greatly appreciated. Thanks.

let user
let computer
let result
//1
function userChoice() {
  let user = prompt(`rock, paper, scissors`)
}

//2
function computersTurn() {
  let randomNumber = Math.floor((Math.random() * 3) + 1);
  switch (randomNumber) {
    case 1:
      computer = `rock`;
      break;
    case 2:
      computer = `scissors`;
      break;
    case 3:
      computer = `paper`;
      break;
  }
}

//3
function decideWinner() {
  if (user == `rock`) {
    switch (computer) {
      case `rock`:
        result = `tie`
        break;
      case 'scissors':
        result = `player`
        break;
      case `paper`:
        result = `computer`
        break;
    }
  } else if (user == `paper`) {
    switch (computer) {
      case `rock`:
        result = `player`
        break;
      case 'scissors':
        result = `computer`
        break;
      case `paper`:
        result = `tie`
        break;
    }
  } else if (user == `scissors`) {
    switch (computer) {
      case `rock`:
        result = `computer`
        break;
      case 'scissors':
        result = `tie`
        break;
      case `paper`:
        result = `player`
        break;
    }
  }
}

userChoice();
computersTurn();
decideWinner();
console.log(result);

12 thoughts on “Javascript switch statement nested inside If statement cannot access other variables and returns Unidentified”

Leave a Comment