Categories
JavaScript Answers

How to Set Boolean Values in JavaScript LocalStorage?

Spread the love

We can only store strings as values in local storage.

Therefore, boolean values are converted to strings.

To check for them, we can write:

localStorage.setItem('value', true)  
const value = localStorage.getItem('value');  
console.log(JSON.parse(value) === true);

We call setItem to store a boolean value with the 'value' key.

Then we get the item with the 'value' key with getItem .

Next, we call JSON.parse to parse that value back into a boolean.

And we check that value with === to see if it equals to true exactly.

The console log logs true so we know value is parsed as true .

We can also check the string directly.

For instance, we can write:

localStorage.setItem('value', true)  
const value = localStorage.getItem('value');  
console.log(value === 'true');

to compare value with 'true' with === .

And we also get true logged.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *