Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have localStorage value of true?

I was wondering if its possible for localStorage to have a Boolean value instead of a string?

Using JS only no JSON if its impossible or can be done in JS a different way please let me know thanks

http://jsbin.com/qiratuloqa/1/

//How to set localStorage "test" to true?

test = localStorage.getItem("test");
localStorage.setItem("test", true); 

if (test === true) {
  alert("works");
} else {
  alert("Broken");
}



/* String works fine.

test = localStorage.getItem("test");
localStorage.setItem("test", "hello"); 

if (test === "hello") {
  alert("works");
} else {
  alert("Broken");
}

*/
like image 304
GoogleFailedMe Avatar asked Mar 08 '15 13:03

GoogleFailedMe


1 Answers

I was wondering if its possible for localStorage to have a Boolean value instead of a string?

No, web storage only stores strings. To store more rich data, people typically use JSON and stringify when storing and parse when retrieving.

Storing:

var test = true;
localStorage.setItem("test", JSON.stringify(test)); 

Retrieving:

test = JSON.parse(localStorage.getItem("test"));
console.log(typeof test); // "boolean"

You don't need JSON for just a boolean, though; you could just use "" for false and any other string for true, since "" is a "falsey" value (a value that coerces to false when treated as a boolean).

like image 50
T.J. Crowder Avatar answered Nov 01 '22 12:11

T.J. Crowder