0

I would like to know how to check a the value of an item stored in local storage is true or false.

This is what i have , but the if statement isnt working.

function setCBT(){
localStorage.setItem('testObject', true);

}


function alertLocalStorage(){
var object = localStorage.getItem('testObject');

if(object == true) {

   alert("This item is true");
}
else {

       alert("This item is false");

}

}
Jess
  • 133
  • 3
  • 12

3 Answers3

3

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.

Thus you need to compare the value with string:

 if(object == "true") {

Here is the Alternative posted by CMS.

Community
  • 1
  • 1
Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
0

You can simply use

if(object) { 
    // true 
}
rjmacarthy
  • 2,164
  • 1
  • 13
  • 22
0

Why not use JSON.parse().The JSON.parse() method parses a string as JSON, optionally transforming the value produced by parsing.

if(JSON.parse(object)) {

   alert("This item is true");
}

Note using JSON.parse()

JSON.parse('{}');              // {}
JSON.parse('true');            // true
JSON.parse('"foo"');           // "foo"
JSON.parse('[1, 5, "false"]'); // [1, 5, "false"]
JSON.parse('null');            // null

JSON.parse()

Sudharsan S
  • 15,336
  • 3
  • 31
  • 49