Home  >  Q&A  >  body text

Implementing localStorage as true: a step-by-step guide.

I wonder if localStorage can have boolean values ​​instead of strings?

Only using JS, not JSON, if it's not possible or can be done in a different way via JS, please let me know, thanks

http://jsbin.com/qiratuloqa/1/

//How to set localStorage "test" to true?

test = localStorage.getItem("test");
localStorage.setItem("test", true); 

if (test === true) {
  alert("works");
} else {
  alert("Broken");
}



/* String works fine.

test = localStorage.getItem("test");
localStorage.setItem("test", "hello"); 

if (test === "hello") {
  alert("works");
} else {
  alert("Broken");
}

*/


P粉195200437P粉195200437361 days ago731

reply all(1)I'll reply

  • P粉197639753

    P粉1976397532023-10-24 09:37:10

    No, Network Storage only stores strings. To store richer data, people often use JSON and stringify when storing and parsing when retrieving.

    storage:

    var test = true;
    localStorage.setItem("test", JSON.stringify(test));

    Search:

    test = JSON.parse(localStorage.getItem("test"));
    console.log(typeof test); // "boolean"

    You don't need JSON to get the boolean value, though; you can just use "" for false and any other string for true, since "" is a " falsey" value (a value that is forced to false when treated as a boolean).

    reply
    0
  • Cancelreply