tags:

views:

62

answers:

4

i noticed that i cannot set boolean values in localStorage?

localStorage.setItem("item1", true);
alert(localStorage.getItem("item1") + " | " + (localStorage.getItem("item1") == true));

always alerts true | false when i try to test localStorage.getItem("item1") == "true" it alerts true ... so no way i can set an item in localStorage to true?

even if its a string, i thought only === will check the type?

so

alert("true" == true); // shld be true? 
+1  A: 

I'm not sure if LocalStorage can save boolean values but I can tell you that when you do alert("true" == true); it will never evaluate to true because you are implicitly comparing a string to a boolean. That is why to set boolean values you use true instead of "true".

Am
What about alert("1"==1)? Javascript is a strange (and inconsistent) beasty.
spender
@Andy: No it's not.
KennyTM
@spender: that's because the right operand is cast to a string for the comparison. `"1" === 1` would actually return false.
Andy E
@Kenny: whoops *facepalm*, thanks for the correction :-) I was mixed up because of how booleans cast to strings.
Andy E
+3  A: 

For the moment, all the implementations Safari, WebKit, Chorme, Firefox and IE, are following an old version of the WebStorage standard, where the value of the storage items can be only a string.

An option would be to use JSON parse and stringify method to serialize and deserialize the data, as I suggested some time ago in another question, for example:

var value = "true";
JSON.parse(value) === true; // true
CMS
+2  A: 
KennyTM
*If either operand is a number or a boolean, the operands are converted to **numbers** if possible* - I totally didn't realize that. I thought if one were a string, the other was cast to a string. Cheers (+1).
Andy E
@Andy, check this [useful notes](http://dmitrysoshnikov.com/notes/note-2-ecmascript-equality-operators/) on the subject.
CMS
@CMS: thanks, a great read.
Andy E
A: 

[Wanted to tack this comment onto CMS’s answer, but I suppose I’m not allowed to yet. :-P]

Here’s a little function I’ve been using to handle the parsing part of this issue (the function will keep doing the Right Thing after the browser implementations catch up with the spec, so no need to remember to change out code later):

function parse(type) {
   return typeof type == 'string' ? JSON.parse(type) : type;
}
byoogle