6

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.

Community
  • 1
  • 1
A. Wolff
  • 74,033
  • 9
  • 94
  • 155

4 Answers4

20

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

Tiesselune
  • 1,701
  • 20
  • 27
5

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

Satpal
  • 132,252
  • 13
  • 159
  • 168
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.

Andrey
  • 4,020
  • 21
  • 35
0

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.

Mac
  • 1,432
  • 21
  • 27