Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

166
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda