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

187
Views
how to check 3 possibilities using only 2 if statements

Create a function that receives an integer as an argument and returns a string such as:

  • if the number is multiple of 4, return "Foo"
  • if the number is multiple of 7, return "Bar"
  • if the number is multiple of 4 and 7, return "FooBar"

This can be done using 3 if statements like below but can this be done only using 2 if statements?

const intToStr = (intVal) => {

    if (intVal % 4 == 0 && intVal % 7 == 0) {
        return "FooBar";
    }
    
    if (intVal % 7 == 0) {
        return "Bar";
    } 
    
    if (intVal % 4 == 0) {
        return "Foo";
    }

}

console.log(intToStr(4*7));
console.log(intToStr(7));
console.log(intToStr(4));

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

0

Yes, it can be done with just 2 if statements.

const intToStr = (intVal) => {
  let str = '';

  if (intVal % 4 === 0) {
    str += "Foo";
  }

  if (intVal % 7 === 0) {
    str += "Bar";
  }
  
  return str;
}

console.log(intToStr(4*7));
console.log(intToStr(7));
console.log(intToStr(4));

about 4 years ago · Juan Pablo Isaza Report

0

Remember that you can sum strings. As value returned in case input is dividable by the same values as in two other ifs, you can just add strings in case input fulfills that condition.

To make it more clear:

var output = '';
if(intVal % 4 === 0)
{
  output = output + 'Foo' ;
}
if(intVal % 7 === 0)
{
  output = output + 'Bar' ;
}

return output;

That way you have two conditions and their cumulative values returned.

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!