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
Is JavaScript Conditional Operator better method for this if/else statement?

I am trying to see if I can reduce the code below with less JavaScript. When the user select Even dropdown option the only differences between that and the else statement is "i = 0" and "i % 2 === 0"

any recommendations? Maybe conditional operator would be best method? thank you

        if (this.selection == "even") {
            for (let i = 0; i <= number; i++) {
                if (i % 2 === 0) 
                this.results.push(i + "\n");
            }
        } else {
            for (let i = 1; i <= number; i++) {
                if (i % 2 !== 0) 
                this.results.push(i + "\n");
            }
        }
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Use this.selection to determine the starting number, then increment by 2 inside the loop instead of i++, so you don't have to check i % 2.

const startAt = this.selection == "even" ? 0 : 1;
for (let i = startAt; i <= number; i += 2) {
    this.results.push(i + "\n");
}
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!