So I was coding a little clicking game and ran into the following issue.
So I’m defining a variable to a localStorage Item.
And everytime I click the button that should add one to the score it adds one to the end of the text. Ex: [ before click: (1) after click: (11)] Why does it does this? You nay think im adding 10 to the variable but check the image ive provided.
2
Answers
Local storage can only store strings. So, when you get the number of clicks from local storage on line 2, if the number of clicks is, for example, 1, it returns
'1'
.'1' + 1
is'11'
, which is why this is happening. A simple fix is to convert the string retrieved from local storage into a number, using theNumber()
function.TLDR:
You should convert the result of
localStorage.getItem
to Number before incrementing it, like this:More details:
I think your are facing this issue because
localStorage
saves all the values asstring
.For example: if you run the following command in the console:
and then:
the value you will get in return will be:
If you want to get the value as a number you would want to convert the return of
localStorage.getItem
toNumber
:or a one liner: