Home > Software engineering >  localStorage differentiate between non-existent key and null value
localStorage differentiate between non-existent key and null value

Time:09-27

In some cases, I need to store information in the localStorage that some 'objects' are null. But it does not support that.

localStorage.setItem('tt', null);
const tt = localStorage.getItem('tt');
console.log(tt.length);
console.log(`tt is ${tt == null ? '' : 'NOT '}null`);

this code puts to console:

4
tt is NOT null

Why?

I can adjust my logic and avoid saving null objects in the storage, but in some circumstances, you want to differentiate data "object's value is unknown" vs "object's value is null".

Should I just use another variable for that?

CodePudding user response:

You can use the in operator to check whether a key exists in localStorage:

localStorage.setItem('tt', null);
const tt = localStorage.getItem('tt');
console.log(tt.length);
console.log(`tt is ${'tt' in localStorage ? '' : 'NOT '}null`);

CodePudding user response:

Based on the Documentation the return value of getItem is a DomString

A DOMString containing the value of the key. If the key does not exist, null is returned.

If you want to say null, you'll need to use JSON.stringify and JSON.parse

localStorage.setItem('tt', JSON.stringify(null));
const tt = JSON.parse(localStorage.getItem('tt'));

console.log(`tt is ${tt == null ? '' : 'NOT '}null`);

  • Related