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

142
Visualizações
JSON.parse an Undefined object from Local Storage

I am having a LocalStorage item which I am parsing into a variable like this:

let resp = JSON.parse(localStorage.getItem('someKey'));

The thing is sometimes, the localStorage may not have the value and it may return an Undefined object to parse which is resulting in following error:

SyntaxError: Unexpected token U in JSON at position 0

I have tried this:

let resp = localStorage.getItem('someKey') ? JSON.parse(localStorage.getItem('someKey')) : null;

But I believe this is not very optimal way of handling this, any suggestions are welcome

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

your solution is just fine, if you want it to be shorter, you could try this

let resp = JSON.parse(localStorage.getItem('someKey') || null)

Here is how it works:

  1. localStorage.getItem('someKey') || null will evaluate the left side of the code first, if localStorage.getItem('someKey') returns undefined or '' empty string, it will return the right side code which is null

  2. Then, JSON.parse(null) will return null instead of error

about 4 years ago · Juan Pablo Isaza Relatório

0

You could try something like this:

let resp = null;
const storedResp = localStorage.getItem('someKey');
if (storedResp) {
  try {
    resp = JSON.parse(storedResp);
  } catch (e) {}
}

This shouldn't generate any errors since you're only parsing it to JSON if it exists, and then catching any errors if JSON parsing fails. You're left with resp being equal to null or the stored data as JSON, with no errors in any case.

As others have said, your current solution is fine, but there are two potential issues with it as written:

  • You access the item in localStorage twice, which may be unnecessarily slow if it is a large object.
  • Many companies prefer (or require) that you wrap lines at 80 characters and your current solution is 96 characters long.
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