Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

167
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
ยฉ 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!