Cannot set boolean values in LocalStorage?
JavascriptJavascript Problem Overview
I noticed that I cannot set boolean values in localStorage
?
localStorage.setItem("item1", true);
alert(localStorage.getItem("item1") + " | " + (localStorage.getItem("item1") == true));
Always alerts true | false
when I try to test localStorage.getItem("item1") == "true"
it alerts true ... How can I set an item in localStorage
to true?
Even if it's a string, I thought only ===
would check the type?
So
alert("true" == true); // should be true?
Javascript Solutions
Solution 1 - Javascript
For the moment, all the implementations Safari, WebKit, Chrome, Firefox and IE, are following the current version of the WebStorage standard, where the value of the storage items can be only a string.
An option would be to use JSON parse
and stringify
method to serialize and deserialize the data, as I suggested some time ago in another question, for example:
var value = "true";
console.log(JSON.parse(value) === true); // true
Solution 2 - Javascript
Firefox's implementation of Storage can only store strings, but on 2009 September, W3C modified the draft to accept any data. The implementation (still) isn't caught up yet (see Edit below).
So in your case the boolean is converted to a string.
As for why "true" != true
, as written in the description of Equal (==
) in MDC*:
> If the two operands are not of the same type, JavaScript converts the operands then applies strict comparison. If either operand is a number or a boolean, the operands are converted to numbers if possible; else if either operand is a string, the other operand is converted to a string if possible.
Note that the string is converted to a Number instead of a Boolean. Since "true"
converted to a number is NaN
, it will not be equal to anything, so false
is returned.
(*: For the actual standard, see ECMA-262 §11.9.3 “The Abstract Equality Comparison Algorithm”)
Edit: The setItem
interface was reverted to accept strings only on the 2011 Sept 1st draft to match the behavior of existing implementations, as none of the vendors are interested in supporting storing non-strings. See https://www.w3.org/Bugs/Public/show_bug.cgi?id=12111 for detail.
Solution 3 - Javascript
My solutions:
function tytPreGetBool(pre) {
return localStorage.getItem(pre) === 'true';
}
Solution 4 - Javascript
This is related to CMS’s answer.
Here’s a little function I’ve been using to handle the parsing part of this issue (the function will keep doing the Right Thing after the browser implementations catch up with the spec, so no need to remember to change out code later):
function parse(type) {
return typeof type == 'string' ? JSON.parse(type) : type;
}
Solution 5 - Javascript
I'd like to point out that it might be kinda easier just to wrap plain boolean value inside object and then, using JSON.stringify
create local storage content and other way around, JSON.parse
to retrive it:
let storeMe = {
myBool: true
}
localStorage.setItem('test', JSON.stringify(storeMe))
let result = JSON.parse(localStorage.getItem('test'))
Solution 6 - Javascript
Use store.js:
localStorage.setItem('isUser', true)
localStorage.getItem('isUser') === "true" //true
npm i -D store
↓
store.get('isUser') //true
Solution 7 - Javascript
What I usually do is just save the value in LocalStore as a Boolean, and then retrieve with a parsing method, just to be sure for all browsers. My method below is customized for my business logic. Sometimes I might store smth as 'no' and still need false
in return
function toBoolean(str) {
if (typeof str === 'undefined' || str === null) {
return false;
} else if (typeof str === 'string') {
switch (str.toLowerCase()) {
case 'false':
case 'no':
case '0':
case "":
return false;
default:
return true;
}
} else if (typeof str === 'number') {
return str !== 0
}
else {return true;}
}
Solution 8 - Javascript
I'm not sure if LocalStorage can save boolean values but I can tell you that when you do alert("true" == true);
it will never evaluate to true because you are implicitly comparing a string to a boolean. That is why to set boolean values you use true
instead of "true"
.
Solution 9 - Javascript
eval
can also be used carefully under some cases.
console.log(eval("true") === true) //true
Solution 10 - Javascript
When I need to store a flag I usually do:
localStorage.f_active = true
(stored value is 'true' and it's fine)
if localStorage.f_active
— passes
and to unflag:
delete localStorage.f_active
if localStorage.f_active
— doesn't pass (returned value is undefined)