Can I conditionally pass a property into an object?

Viewed 42

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

2 Answers

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()

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();
}

Related