I was wondering if its possible for localStorage to have a Boolean value instead of a string?
Using JS only no JSON if its impossible or can be done in JS a different way 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");
}
*/
I was wondering if its possible for localStorage to have a Boolean value instead of a string?
No, web storage only stores strings. To store more rich data, people typically use JSON and stringify when storing and parse when retrieving.
Storing:
var test = true;
localStorage.setItem("test", JSON.stringify(test));
Retrieving:
test = JSON.parse(localStorage.getItem("test"));
console.log(typeof test); // "boolean"
You don't need JSON for just a boolean, though; you could just use ""
for false and any other string for true, since ""
is a "falsey" value (a value that coerces to false when treated as a boolean).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With