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

233
Visualizações
Use only the variable that caused an if statement to trigger, within the if statement

say you have an if statement:

try {
    if (!a || !b || !c || !d) {
      let nullVariable = ???;
      // use the variable that is null
      throw nullVariable
    }
} catch (ex) {
  log.debug(`${ex} is not defined`);
}

Is there a built in way to see which variable was set to null, without creating an if statement for each individual variable?

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

0

You can put the assignment inside the if condition expression.

let a, b, c, d;
a = 3;
b = "foo";
d = {x: 10};
let nullVariable = (!a && 'a') || (!b && 'b') || (!c && 'c') || (!d && 'd');
if (nullVariable) {
    console.log(`${nullVariable} is not defined`);
}

about 4 years ago · Juan Pablo Isaza Relatório

0

You can extract the variable name using object shorthand.

const fn = ({ a, b, c, d }) => {
  let nullVariable = Object.entries({ a, b, c, d }).find(([_, val]) => !val)?.[0];
  
  if(nullVariable)
    console.log(nullVariable + ' is falsy');
};

fn({ a: 1, c: 2, d: 3 });
fn({ a: 1, b: 2, c: 3 });
fn({ a: 1, b: 2, c: 3, d: 4 });

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