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

138
Visualizações
Is there a way to check for falsy values from an array?

I want to check a bunch of variables for falsy values.

Instead of writing a very long if statement, e.g.:

if (!userData.email || !userData.lastName || ! userData.firstName etc...

I wanted to put these values in an array and simply check the array, e.g.:

      var detailsConditionsArr = [
        userData.firstName,
        userData.lastName,
        userData.email,
        userData.phone,
        userData.address,
        userData.mailAddress,
      ]

      if (detailsConditionsArr.indexOf(false) === 1) {
        console.log("Found a falsy");
      }

But the above doesn't work (if statement never fires).

The values could be false, null or ''.

Is there a way to check these from the array?

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

0

Ideal use case for Array#some

Check for falsy value in the iteration, if the test succeeds, true will be returned.

var A = ["Name", ""];
var B = ["Name", "30"];
var C = ["Name", "30", null];

if (A.some(el => !el)) {
  console.log("Found a falsy in A");
}

if (B.some(el => !el)) {
  console.log("Found a falsy in B");
}

if (C.some(el => !el)) {
  console.log("Found a falsy in C");
}

about 4 years ago · Juan Pablo Isaza Relatório

0

You can use the key names you want to check as an array, then do the check like this:

const userData = { email: '', lastName: '', firstName: '' };
const hasFalsy = ['email', 'lastName', 'firstName'].some(k => !Boolean(userData[k]));

if (hasFalsy) {
  console.log('found a falsy');
}

about 4 years ago · Juan Pablo Isaza Relatório

0

You can use reduce to return a single value from the array like so:

var detailsConditionsArr = [
    userData.firstName,
    userData.lastName,
    userData.email,
    userData.phone,
    userData.address,
    userData.mailAddress,
  ]

if (detailsConditionsArr.reduce((carry, el)=> el ? carry : true, false)) {
  console.log("Found a falsy");
}
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