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

165
Visualizações
Can I conditionally pass a property into an object?

Is it possible to conditionally pass a property into an object-based function:

myFunction
      .x()
      .y()
      .x();

Here, I'd like to only pass in y() based on a condition, something like:

myFunction
      .x()
      [isTrue && y()]
      .x();

Any help much appreciated, thanks 🙂

almost 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

You could use that syntax if you wanted to choose between different methods dynamically. But there's no "do nothing" method that you can substitute in place of y when the condition is false.

Use an if statement instead.

let temp = myFunction.x();
if (isTrue) {
    temp = temp.y();
}
temp.x()
almost 4 years ago · Santiago Trujillo Relatório

0

Here's another solution that is more like what you originally imagined. Barmar's solution will work just fine, but I thought I'd show a different approach more like you imagined:

obj
  .x()
  [doIt ? "y" : "noop"]()
  .x();

In this scheme, doIt is any boolean or boolean expression and .noop() is a "do nothing" method on the object.

And, here's a working example you can run in a snippet:

const obj = {
    x() {
        console.log("executing x() method");
        return this;
    },
    y() {
        console.log("executing y() method");
        return this;
    },
    noop() {
        console.log("executing noop() method");
        return this;
    }
}

// try both values of the boolean
for (let doIt of [true, false]) {
    console.log(`\nresults for doIt = ${doIt}`);
    obj
        .x()
        [doIt ? "y" : "noop"]()
        .x();
}

almost 4 years ago · Santiago Trujillo 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