Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

196
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda