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

81
Views
Recode by not using conditional

The below function works good by if statements , I want the same functionality by using without condition statements.

Hello(x){
    If(x<0){
       Console.log("greater");
    }Else{
       Console.log("smaller");
    }
};

Hello(1);
Hello(-1);
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

You could use an Object but it's odd. An if...else statement or it's shorter ternary form more clearly conveys the logic at play which is always preferable.

function Hello(x) {
  const lt = {
    true: "smaller",
    false: "greater"
  };

  console.log(lt[x < 0]);
};

Hello(1);
Hello(-1);

about 4 years ago · Juan Pablo Isaza Report

0

This is probably a stupid thing to actually do and might be overly specific to your example but...:

const hello = (x) => {
  const lt = x < 0;
  console.log("greater".repeat(lt) + "smaller".repeat(1 - lt));
};

hello(-1);
hello(1);

Borrowing from @Teemu's comment a slightly more flexible thing could be:

const if_else = (cond_fn, if_fn, else_fn = (x) => x) =>
  [else_fn, if_fn][+cond_fn()]();

const hello = (x) =>
  if_else(
    () => x < 0,
    () => console.log('greater'),
    () => console.log('smaller')
  );

hello(-1);
hello(1);

about 4 years ago · Juan Pablo Isaza Report

0

@Teemu explained how to do it without branching, and there are times where that can be beneficial (example: Why is processing a sorted array faster than processing an unsorted array?).

function hello(x) {
  console.log(['greater', 'smaller'][+(x < 0)]);
}

hello(1);
hello(-1);

but by definition you cannot achieve behavior based on a condition without a conditional.

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!