Open unevtable opened 1 week ago
Its working correctly I don't think there is any error
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 ...
i am using edge and it is the latest version
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 };
can you please explain this
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 by
parsemethod therefore will result overall to return the default object passed after the
JSON.parse` call due that the first part of statement is null
Hope that this was clear enough to address the issue