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?

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.

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