xRobot
xRobot

Reputation: 26567

How to reduce the number of if

Is there a way to reduce the number of "if" in this code?

function test(input) {
  if ((input % 3 == 0) && (input % 5 == 0)) {
    return 'fizzbuzz';
  } else if (input % 3 == 0) {
    return 'fizz';
  } else if (input % 5 == 0) {
    return 'buzz';
  } else {
    return '' + input;
  }
}


for (var i = 1; i < 100; i++) {
  console.log(test(i));
}

Upvotes: 1

Views: 81

Answers (4)

Jasna Todorovic
Jasna Todorovic

Reputation: 41

You can get rid of the first "if" altogether, because 3 and 5 and "fizz" and "buzz" are used in the later ones. You can also wait to return until the end. Something like:

var str = "";

if (input % 3 === 0){
  str +="fizz";
}

if (input % 5 === 0 ){
  str +="buzz";
} else {
str = input;
}

return str;

Upvotes: 0

Bartek Banachewicz
Bartek Banachewicz

Reputation: 39370

You can avoid that by storing the comparison values:

var mod3 = input % 3 == 0;
var mod5 = input % 5 == 0;

... creating a lookup table ...

var outs = [input, "fizz", "buzz", "fizzbuzz"];

... and indexing it ...

return outs[(+mod3) + 2 * (+mod5)];

... no ifs!

Upvotes: 3

ergonaut
ergonaut

Reputation: 7057

You can use the ternary operator:

return ((input%3==0)&&(input%5==0)) ? 'fizz buzz'
       : (input%3==0) ? 'fizz'
       : (input%5==0) ? 'buzz'
       : '' + input;

Upvotes: 1

loujaybee
loujaybee

Reputation: 96

If you don't want to use if's why not try case syntax?

http://www.w3schools.com/js/js_switch.asp

Alternatively use the JS shorthand for if

so that:

var something;

if (2 + 2 === 4){
 something = "Yup!"
} else {
 something = "Nope"
}

becomes

var something = 2 + 2 === 4 ? "Yup!" : "Nope";

Upvotes: 0

Related Questions