Cannot set boolean values in LocalStorage?

Viewed 137751

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 ... How can I set an item in localStorage to true?

Even if it's a string, I thought only === would check the type?

So

alert("true" == true); // should be true? 
10 Answers

I'd like to point out that it might be kinda easier just to wrap plain boolean value inside object and then, using JSON.stringify create local storage content and other way around, JSON.parse to retrive it:

let storeMe = {
  myBool: true
}

localStorage.setItem('test', JSON.stringify(storeMe))
let result = JSON.parse(localStorage.getItem('test'))

What I usually do is just save the value in LocalStore as a Boolean, and then retrieve with a parsing method, just to be sure for all browsers. My method below is customized for my business logic. Sometimes I might store smth as 'no' and still need false in return

function toBoolean(str) {
    if (typeof str === 'undefined' || str === null) {
        return false;
    } else if (typeof str === 'string') {           
        switch (str.toLowerCase()) {
        case 'false':
        case 'no':
        case '0':
        case "":
            return false;
        default:
            return true;
        }
    } else if (typeof str === 'number') {
        return str !== 0
    }
    else {return true;}
}

When I need to store a flag I usually do:
localStorage.f_active = true (stored value is 'true' and it's fine)
if localStorage.f_active — passes

and to unflag:
delete localStorage.f_active
if localStorage.f_active — doesn't pass (returned value is undefined)

Related