I need help with LocalStorage (I'm a newbiw and a dummy)

<!DOCTYPE html>
<html>
  <head>
    <title>Rock Paper Scissors</title>
  </head>
  <body>
    <p>Rock Paper Scissors</p>
    <button onclick="
      playGame('rock');
    ">Rock</button>

    <button onclick="
      playGame('paper');
    ">Paper</button>

    <button onclick="
      playGame('scissors');
    ">Scissors</button>

    <p class="js-result"></p>
    <p class="js-moves"></p>
    <p class="js-score"></p>

    <button onclick="
      score.wins = 0;
      score.losses = 0;
      score.ties = 0;
      localStorage.removeItem('score');
      updateScoreElement();
    ">Reset Score</button>

    <script>
      let score = JSON.parse(localStorage.getItem('score')) || {
        wins: 0,
        losses: 0,
        ties: 0
      };

      updateScoreElement();

      /*
      if (!score) {
        score = {
          wins: 0,
          losses: 0,
          ties: 0
        };
      }
      */

      function playGame(playerMove) {
        const computerMove = pickComputerMove();

        let result = '';

        if (playerMove === 'scissors') {
          if (computerMove === 'rock') {
            result = 'You lose.';
          } else if (computerMove === 'paper') {
            result = 'You win.';
          } else if (computerMove === 'scissors') {
            result = 'Tie.';
          }

        } else if (playerMove === 'paper') {
          if (computerMove === 'rock') {
            result = 'You win.';
          } else if (computerMove === 'paper') {
            result = 'Tie.';
          } else if (computerMove === 'scissors') {
            result = 'You lose.';
          }
          
        } else if (playerMove === 'rock') {
          if (computerMove === 'rock') {
            result = 'Tie.';
          } else if (computerMove === 'paper') {
            result = 'You lose.';
          } else if (computerMove === 'scissors') {
            result = 'You win.';
          }
        }

        if (result === 'You win.') {
          score.wins += 1;
        } else if (result === 'You lose.') {
          score.losses += 1;
        } else if (result === 'Tie.') {
          score.ties += 1;
        }

        localStorage.setItem('score', JSON.stringify(score));

        updateScoreElement();

        document.querySelector('.js-result').innerHTML = result;

        document.querySelector('.js-moves').innerHTML = `You ${playerMove} - ${computerMove} Computer`;
      }

      function updateScoreElement() {
        document.querySelector('.js-score')
          .innerHTML = `Wins: ${score.wins}, Losses: ${score.losses}, Ties: ${score.ties}`;
      }

      function pickComputerMove() {
        const randomNumber = Math.random();

        let computerMove = '';

        if (randomNumber >= 0 && randomNumber < 1 / 3) {
          computerMove = 'rock';
        } else if (randomNumber >= 1 / 3 && randomNumber < 2 / 3) {
          computerMove = 'paper';
        } else if (randomNumber >= 2 / 3 && randomNumber < 1) {
          computerMove = 'scissors';
        }

        return computerMove;
      }
    </script>
  </body>
</html>

This is the code my YouTube teacher used to create rock paper scissors game. My problem is, score shows undefined. It worked just fine before LocalStorage lessons…I asked ChatGPT and Bard for help too and the YouTube channel is remains unresponsive.
Can someone help me? I’m 100% sure it’s some dumbass error I’m missing.

Hey there,

I just tested your code, and it seems to work just fine to me here:

Can you upload a screenshot showing the score is undefined? Also, do you know how to check for the local storage values using the browser dev tools?

Hey there, thanks for responding I’m surprised someone’s interested in helping out at all!

First of all I suck 100% so do keep in mind my thick skull :smiley:

I’m uploading two images (again, because I’m a dummy and not fully certain what you want to see) for you to review:

AGAIN! Thank you for reaching out man!

Here’s another (new users can upload one at a time):

I guessed my localstorage is somehow fried, but I couldn’t search for a fix.

I got exactly the same result as you (undefined). I was about to write a reply, then I changed some code, the pen refreshed, and then everything worked. So your storage isn’t fried, there’s some tiny error in the logic that I can’t see atm, I’ll try to replicate the issue

1 Like

It’s okay man, sometimes we all need a little help :slight_smile:

Hmm I can see that the key ‘score’ isn’t available in your local storage, but I’m not sure why.

By the way you can remove data from local storage manually by right-clicking on the key value and then click delete:

Maybe you can try emptying the local storage, then copy paste the code you’ve posted earlier and refresh the page?

You can try this code

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Rock Paper Scissors</title>
</head>
<body>

<button onclick="playGame('rock')">Rock</button>
<button onclick="playGame('paper')">Paper</button>
<button onclick="playGame('scissors')">Scissors</button>

<p class="js-result"></p>
<p class="js-moves"></p>
<p class="js-score"></p>

<button onclick="resetScore()">Reset Score</button>

<script>
  let score = JSON.parse(localStorage.getItem('score')) || { wins: 0, losses: 0, ties: 0 };

  updateScoreElement();

  function playGame(playerMove) {
    const computerMove = pickComputerMove();

    let result = '';

    if (playerMove === 'scissors') {
      if (computerMove === 'rock') {
        result = 'You lose.';
      } else if (computerMove === 'paper') {
        result = 'You win.';
      } else if (computerMove === 'scissors') {
        result = 'Tie.';
      }

    } else if (playerMove === 'paper') {
      if (computerMove === 'rock') {
        result = 'You win.';
      } else if (computerMove === 'paper') {
        result = 'Tie.';
      } else if (computerMove === 'scissors') {
        result = 'You lose.';
      }
      
    } else if (playerMove === 'rock') {
      if (computerMove === 'rock') {
        result = 'Tie.';
      } else if (computerMove === 'paper') {
        result = 'You lose.';
      } else if (computerMove === 'scissors') {
        result = 'You win.';
      }
    }

    if (result === 'You win.') {
      score.wins += 1;
    } else if (result === 'You lose.') {
      score.losses += 1;
    } else if (result === 'Tie.') {
      score.ties += 1;
    }

    localStorage.setItem('score', JSON.stringify(score));

    updateScoreElement();

    document.querySelector('.js-result').innerHTML = result;
    document.querySelector('.js-moves').innerHTML = `You ${playerMove} - ${computerMove} Computer`;
  }

  function updateScoreElement() {
    document.querySelector('.js-score').innerHTML = `Wins: ${score.wins}, Losses: ${score.losses}, Ties: ${score.ties}`;
  }

  function resetScore() {
    score.wins = 0;
    score.losses = 0;
    score.ties = 0;
    localStorage.removeItem('score');
    updateScoreElement();
  }

  function pickComputerMove() {
    const randomNumber = Math.random();

    let computerMove = '';

    if (randomNumber >= 0 && randomNumber < 1 / 3) {
      computerMove = 'rock';
    } else if (randomNumber >= 1 / 3 && randomNumber < 2 / 3) {
      computerMove = 'paper';
    } else if (randomNumber >= 2 / 3 && randomNumber < 1) {
      computerMove = 'scissors';
    }

    return computerMove;
  }
</script>

</body>
</html>

I tried a different browser and it worked, though code itself works wrong and I have to recheck.
I’ll try fixing the issue on chrome too, will get back to you with an
update!
How odd though that neither google search result nor ChatGPT/Bard had advised me to try different browser.
I guess I should’ve figured that one out myself. Baby steps.

I tried a different browser and it worked, though code itself works wrong and I have to recheck.

Yeah but if I don’t understand how/why/where it works/doesn’t work, what’s the point of this thing?

let score;
try {
  score = JSON.parse(localStorage.getItem('score')) || { wins: 0, losses: 0, ties: 0 };
} catch (error) {
  console.error('Error parsing score from localStorage:', error);
  score = { wins: 0, losses: 0, ties: 0 };
}

By initializing the score variable at the beginning of your script, you can avoid the “Uncaught ReferenceError: score is not defined” issue.

code pen

I will delete the pen after …

I updated the code per your instructions. It works in edge, same error in Chrome.

1 Like

Hmm that’s really strange. Can you test the code by opening Chrome in incognito?

Edge pretty much is Chrome with a different skin, it would work in both unless you have some extension or setting in Chrome blocking it. Make sure you are not blocking third-party cookies in Chrome and run it without extensions using Incognito mode.

Look in the console as well for errors and post what you see.