Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

localStorage and boolean 'string'

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.

like image 701
A. Wolff Avatar asked Jun 04 '15 12:06

A. Wolff


3 Answers

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

like image 81
Tiesselune Avatar answered Nov 17 '22 21:11

Tiesselune


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

like image 5
Satpal Avatar answered Nov 17 '22 22:11

Satpal


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.

like image 3
Andrey Avatar answered Nov 17 '22 21:11

Andrey