Cannot set boolean values in LocalStorage?

Firefox's implementation of Storage can only store strings, but on 2009 September, W3C modified the draft to accept any data. The implementation (still) isn't caught up yet (see Edit below).

So in your case the boolean is converted to a string.

As for why "true" != true, as written in the description of Equal (==) in MDC*:

If the two operands are not of the same type, JavaScript converts the operands then applies strict comparison. If either operand is a number or a boolean, the operands are converted to numbers if possible; else if either operand is a string, the other operand is converted to a string if possible.

Note that the string is converted to a Number instead of a Boolean. Since "true" converted to a number is NaN, it will not be equal to anything, so false is returned.

(*: For the actual standard, see ECMA-262 §11.9.3 “The Abstract Equality Comparison Algorithm”)


Edit: The setItem interface was reverted to accept strings only on the 2011 Sept 1st draft to match the behavior of existing implementations, as none of the vendors are interested in supporting storing non-strings. See https://www.w3.org/Bugs/Public/show_bug.cgi?id=12111 for detail.


My solutions:

function tytPreGetBool(pre) {
    return localStorage.getItem(pre) === 'true';
}

For the moment, all the implementations Safari, WebKit, Chrome, Firefox and IE, are following the current 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";
console.log(JSON.parse(value) === true); // true

Tags:

Javascript