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

115
Views
How to define function conditionally

I want to set a function to the result of a ternary operator (that is returning one of two functions) and then call the result. My code looks like this:

const bar = (x: number) => {
  // do something
}

const foo = (x: number) => {
  // do something else
}

const my_function = condition ? bar : foo;

my_function(x)

but I get a type error that my_function is not a function. Why doesn't this work, and how can I make it work? I have to call this function many times which is why I want to do it like this and not just call conditionally.

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

0

@m-s7's answer works. However, it's kind of messy.

IMHO better to commit something like this to production instead:

const bar = (x: number) => {
  // do something
}

const foo = (x: number) => {
  // do something else
}

const my_function = (x: number) => condition ? bar(x) : foo(x)

Here, you are creating a function in which you pass in the arg and return the result from the correct function based on the condition. It's pretty clean and easy to understand at a glance.

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!