localStorage and boolean 'string'
Solution 1
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
Solution 2
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);
Solution 3
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.
Related videos on Youtube
Comments
-
A. Wolff over 1 year
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.