Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

194
Views
localStorage differentiate between non-existent key and null value

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?

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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`);

about 4 years ago · Juan Pablo Isaza Report

0

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.

about 4 years ago · Juan Pablo Isaza Report

0

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`);
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!