Storing boolean value in localStorage, this value is converted to string.
Now trying to converting back this value from localStorage to boolean, i need to use JSON.parse()
method, the more handy !!
doesn't work.
Code sample:
var test = false;
localStorage['test'] = test;
console.log("JSON.parse returns: ", JSON.parse(localStorage['test']), "expected: ", test);
console.log("'!!' returns: ", !! localStorage['test'], "expected: ", test);
I'm quite confused why this behaviour. Any explaination?
PS: using getter/setter localStorage methods doesn't matter here, same result.
Local storage stores strings , I'm afraid, whatever the input (if you feed it with an object, it will be converted automatically with its standard toString()
method)... So you're doing !! test
on a string, which is always true
.
You should always use JSON.stringify()
and JSON.parse()
when dealing with what you store in DOM storage
Use JSON.stringify()
when save the object. As you know it will convert JavaScript value to a JSON string so when using JSON.parse()
its converted back properly.
localStorage['test'] = JSON.stringify(test);
DEMO
This happens because any stored value in localstorage is a string.
So you've perofming !!"false"
and !!
is always true
for non-empty string.
To be able to store non-string values in localStorage you have to always use JSON.
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