skip to Main Content

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.

The Code (Html)

2

Answers


  1. 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 the Number() function.

    console.log('1' + 1); // logs '11'
    console.log(Number('1') + 1); // logs 2
    Login or Signup to reply.
  2. TLDR:

    You should convert the result of localStorage.getItem to Number before incrementing it, like this:

    var Clicks = Number(localStorage.getItem("mystats"));
    Clicks = Clicks + 1;
    

    More details:

    I think your are facing this issue because localStorage saves all the values as string.

    For example: if you run the following command in the console:

    localStorage.setItem("test", 123);
    

    and then:

    localStorage.getItem("test");
    

    the value you will get in return will be:

    `123`
    

    If you want to get the value as a number you would want to convert the return of localStorage.getItem to Number:

    const testValue = localStorage.getItem("test");
    const testNumber = Number(testValue);
    

    or a one liner:

    Number(localStorage.getItem("test"));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search