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?
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`);
based on the documentation the setItem receives the DOMString which converts null to string "null". That's why when you save null you get length 4.
https://developer.mozilla.org/en-US/docs/Web/API/DOMString
Certain Web APIs accepting a DOMString have an additional legacy behavior, where passing null stringifies to the empty string instead of the usual "null".
If you want set null I would use removeItem("tt") to get null value.
localStorage can only store string key/value pairs; thus null will be converted to string form ('null') when you set the item in localStorage.
Using strict type checking when comparing to null will solve the problem:
localStorage.setItem('tt', null);
const tt = localStorage.getItem('tt');
console.log(`tt is ${tt === null ? '' : 'NOT '}null`);
Alternatively, you can use the in operator to check whether the key exists:
console.log(`tt is ${'tt' in localStorage ? 'NOT' : ''} null`);