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

206
Visualizações
Why JavaScript null check doesn't working?
function readProperty(property)
{
  console.log(localStorage[property]) //Alerts “null”
  if(localStorage[property] == null)
  {
      console.log('Null chek')
      return false;
  }

  return localStorage[property];
}

log outputs "null", but 'if()' doesn't work. I try with ===, its not work too. Help please.

UPD: Thanks everyone this change helped me if(localStorage[property] == 'null')

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

0

The keys and the values stored with localStorage are always in the UTF-16 string format, which uses two bytes per character. As with objects, integer keys are automatically converted to strings.

https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

Try:

localStorage[property] === 'null'
about 4 years ago · Juan Pablo Isaza Relatório

0

Although: console.log(localStorage[property]) may report null, the actual value is undefined.

So, in your if statement, if you test against undefined, you'll get a match.

Better yet though, just test for the existence or non existence of a value with:

 if(localStorage[property])...  // Tests for any "truthy" value

or

 if(!localStorage[property])...  // Tests for any "falsey" value
about 4 years ago · Juan Pablo Isaza Relatório

0

Well, I don't know if you're trying to use the global localStorage or if it's a defined variable in your code.

If you're using the localStorage API, you should check if a key exists like this...

if (!localStorage.getItem("my-item")) {
  console.log("item doesn't exist.");
}

The .getItem() method returns null when the key isn't defined so checking using ! or item !== null work.

.getItem() reference from MDN, https://developer.mozilla.org/en-US/docs/Web/API/Storage/getItem.

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