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

168
Views
How to optionally add a method to a chain in javascript?

I have this chain of methods

MyObject.methodA().methodB().methodC()

Suppose I want methodB() to be added or changed based on some condition:

const inclueMethodB = false;
// change method based on condition
MyObject.methodA().(inclueMethodB ? methodB() : method123()).methodC()
// add method based on condition
MyObject.methodA().(inclueMethodB && methodB()).methodC()

Is there a way to do this in javascript?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

I can't think of a way to optionally call a method like that.

If you were choosing between two methods, you could use a subscript where the method name is specified dynamically:

MyObject.methodA()[includeB1 ? "methodB1" : "methodB2"]().methodC()

You could achieve your original goal by defining a method that doesn't do anything except return the same thing that methodB() does. If this is a fluent interface where all the methods just return this, it could be:

doNothing() {
    return this;
}

Then you could write:

MyObject.methodA()[includeB ? "methodB" : "doNothing"]().methodC()

But this all seems unnecessarily complex and confusing. Just use ordinary if statements, which express the intent clearly:

let temp = MyObject.methodA();
if (includeB) {
    temp = temp.methodB();
}
temp.methodC();
about 4 years ago · Juan Pablo Isaza 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!