SuperSimpleDev / javascript-course

579 stars 465 forks source link

exercise 8k i checked my code and its the same but still giving error #132

Open unevtable opened 1 week ago

unevtable commented 1 week ago
<!DOCTYPE html>
<html>

<head>
  <title>Coin Flip</title>
</head>

<body>
  <button onclick="
    playGame('HEADS');
  ">Heads</button>
  <button onclick="
    playGame('TAILS');
  ">Tails</button>

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

    function playGame(guess) {
      const randomNumber = Math.random();
      const result = randomNumber < 0.5 ? 'HEADS' : 'TAILS';

      console.log(`ITS ${result}!`);

      console.log(guess === result ? 'You Win!' : 'You Lose!');

      guess === result ? score.wins++ : score.losses++;
      console.log(score);

      localStorage.setItem('score', JSON.stringify(score));
    }
  </script>
</body>

</html>
unevtable commented 1 week ago

image

kavin00111 commented 1 week ago

Its working correctly I don't think there is any error

MoudiZd commented 1 week ago

I think its about javascript version inside browser

What is the browser you are using and which version, btw try to update your browser than run your code i think it must works ...

unevtable commented 1 week ago

i am using edge and it is the latest version

MoudiZd commented 1 week ago

Try to change this line : const score = JSON.parse(localStorage.getItem('score')) || { wins: 0, losses: 0 };

into

const score = JSON.parse(localStorage.getItem('score')||null) || { wins: 0, losses: 0 };

unevtable commented 5 days ago

can you please explain this

MoudiZd commented 5 days ago

can you please explain this

First let tell what is the problem:

Using JSON.parse(null); will result null, while using JSON.parse(undefined); throws an exception and stop the script

For some reason using localStorage.getItem('score'); on microsoft edge returns undefined (browser specific behavior...)

So using : JSON.parse(localStorage.getItem('score')) || {wins: 0,losses: 0};

Will be equal to: JSON.parse(undefined) || {wins: 0,losses: 0}

And because: JSON.parse(undefined) throws an error this leads to not be fallen back to the passed default object, but instead stop the script

For that we will try to find a way that letJSON.parse not stop the script but results null instead when the passed argument is undefined, and this can be done by adding || null to the argument passed to JSON.parse call

To become: JSON.parse(localStorage.getItem('score')||null) || { wins: 0, losses: 0 };

In this way the script will not be stopped due passing undefined to JSON.parse call, because it will see that we are passing null instead of undefined (because undefined || null = null) which is acceptable byparsemethod therefore will result overall to return the default object passed after theJSON.parse` call due that the first part of statement is null

Hope that this was clear enough to address the issue