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

165
Views
(JavaScript) Best was to check for multiple conditions and end execution as soon as one returns false?

I am currently working on a duty rota App. I need to calculate which employee can work on every particular day of the month. This must also be updated "on the fly" since if someone gets assigned to work on day 1, he/she for example can't work on day 2.

If someone can work on a day or not depends on multiple conditions. My Idea is, to have a "controller"-function which checks, if any of the "conditions"-functions returns false = that means, the person is not available for that day.

I fond a way by simply multiplying the return-values like

const controller = (day, employee) => {
  return (
   cond1(day, employee) * 
   cond2(day, employee) * 
   cond3(day, employee) * 
   cond4(day, employee) * 
   cond5(day, employee)
  )
}

since true == 1 and false == 0 it returns 0 as soon as one condition is false. But I thought this might not be the most efficient way because it checks for all conditions. I am looking for a way to return as soon as one condition is false.

I could use if-else but this would become unreadable condition-hell very fast

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

0

&& will shortcircuit if the first value is false. Try this out:

function foo() {
  console.log('called foo');
  return false;
}
function bar() {
  console.log('called bar');
  return true;
}

foo() && bar()

The output should only be called foo. Shortcircuiting means that the boolean expression will only evaluate as much as it needs to; if the left side of the && is false, then the expression is false, and the right side doesn't need to be evaluated. Note that this also happens with ||, but in the opposite way: if the left side of the expression is true, the right side isn't evaluated.

If all the functions take the exact same arguments as your example implies, you could use [].every, which also "short circuits" by ending iteration early. I would caution against this for your specific example, though, as it can make things hard to maintain in the event that even one of those cond functions takes different parameters.

[cond1, cond2, cond3, cond4, cond5].every((cond) => cond(day, employee))
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!