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);
-jsFiddle-
I'm quite confused why this behaviour. Any explaination?
PS: using getter/setter localStorage methods doesn't matter here, same result.
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);
-jsFiddle-
I'm quite confused why this behaviour. Any explaination?
PS: using getter/setter localStorage methods doesn't matter here, same result.
Share Improve this question edited Jun 20, 2020 at 9:12 CommunityBot 11 silver badge asked Jun 4, 2015 at 12:46 A. WolffA. Wolff 74.4k9 gold badges96 silver badges156 bronze badges 2 |4 Answers
Reset to default 20Local 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.
What you want to do is simple with localDataStorage, where you can transparently set/get any of the following "types": Array, Boolean, Date, Float, Integer, Null, Object or String.
[DISCLAIMER] I am the author of the utility [/DISCLAIMER]
Examples:
localDataStorage.set( 'test', false );
localDataStorage.get( 'test' ); --> false
All of the conversion work is done in the background for you: just set/get and go.
!!"false"===true
– epascarello Commented Jun 4, 2015 at 12:50