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

96
Visualizações
how to make the javascript null check more clear

I am using this code to check a variable in javascript useable:

var userName;
if (userName === null 
|| userName === '' 
|| userName === undefined 
|| userName === {}) {
   console.log("useable");
}else{
    console.log("unuseable");
}

is there any simple and clear way to do this action? If I use if(userName){}, this would not work:

var userName='';
if (userName) {
    console.log("null");
}else{
    console.log("not null");
}

if I use Object.keys(obj).length === 0, this would not work:

var obj=new Date();
if (Object.keys(obj).length === 0) {
    console.log("null");
}else{
    console.log("not null");
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can try a functional approach, including all of your conditions and checks in the function:

function isNull (value) {
  // any falsy value: https://developer.mozilla.org/en-US/docs/Glossary/Falsy
  if (!value) return true;
  if (typeof value === 'object') {
    // empty array
    if (Array.isArray(value) && value.length === 0) return true;
    // empty object
    if (value.toString() === '[object Object]' && JSON.stringify(value) === '{}') return true;
  }
  return false;
}

let username;

if (isNull(username)) {
  console.log('usable');
}
else {
  console.log('not usable');
}

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