javascriptlocal-storage

Can you save something in LocalStorage with a variable?


So this is a quick question, but I was unable to find an answer anywhere. I know to save things in localStorage you write like this:

localStorage.name = JSON.stringify("this has now been saved under name);

But I want to be able to change what it is saved under depening on a variable, like this:

const banana = potato
localStorage.banana = JSON.stringify("this has now been saved under potato");

Is this possible to do? :) ​​​​​​​


Solution

  • Localstorage allows for the storage of key and value pairs where the value is a string.

    If you are assigning to localstorage from reference to another variable, if it resolves to a string then that will work:

    const potato = "potato";
    const banana = potato;
    localStorage.setItem(banana, "this has now been saved under potato");
    

    Otherwise you will need to stringify the value of the variable first.

    https://www.w3schools.com/html/html5_webstorage.asp