Home > Mobile >  I am doing an if statement with multiples of a number
I am doing an if statement with multiples of a number

Time:10-14

I am doing an exercise, the problem is that my if/else structure does not work properly and I do not know why.

Here is the exercise statement and my code

Your task is to write a function, fizzBuzz, that accepts a number and returns a string:

'fizz' if the number is divisible by 3;
'buzz' if the number is divisible by 5;
'fizzbuzz' if the number is divisible by both 3 and 5.
'{number}' if the number doesn't fulfil any of the above conditions.
function fizzBuzz(number) {

  if (number % 3 === 0) {
    return "fizz"
  };
  if (number % 5 === 0) {
    return "buzz"
  };
  if (number % 3 === 0 && number % 5 === 0) {
    return "fizzbuz"
  };
  else return number
}

CodePudding user response:

Try a little mental debugging. Look at your code and run different values through it in your mind:

  • What happens if you run the value 6 through it?
  • What happens if you run the value 10 through it?
  • What happens if you run the value 15 through it?

Ask yourself, "How could I fix this?" (hint: order of operations is important).

Something like this would do what you expect:

function fizzBuzz(n) {
  const fizz = n % 3 ? '' : 'fizz' ;
  const buzz = n % 5 ? '' : 'buzz' ;

  return !fizz && !buzz ? '{number}' : `${fizz}${buzz}` ;

}

or this:

function fizzBuzz( n ) {
  let s;

  if ( n % 3 === 0 ) {
    s = 'fizz' ;
    if ( n % 5 === 0 ) {
      s = 'fizzbuzz' ;
    }
  } else if ( n % 5 == 0 ) {
    s = 'buzz' ;
  } else {
    s  = '{number}' ;
  }

  return s;
}

This does [at most] 2 divisions and 2 comparisions.

The former does 2 divisions and 3-4 comparisons, so it is nominally less efficient.

But I know which version I'd rather look at.

CodePudding user response:

The problem is, if a number is divisible by 5 and 3 (ex 15) "fizz" would only be returned (as a factor of 3) because every block {...} terminates the function with a return (this technique is called a "short-circuit", which isn't a bad practice). So you need to put the 5 and 3 condition first. Also that condition had an undefined variable called solution so that would've been the first error. One minor thing is that each block {...} was suffixed with a semi-colon: ; which is just bad formatting but it doesn't affect functionality.

function fB(number) {
  if (number % 3 === 0 && number % 5 === 0) {
    return "fizzbizz";
  }
  if (number % 3 === 0) {
    return "fizz";
  }
  if (number % 5 === 0) {
    return "bizz";
  }
  return number;
}

console.log(fB(15));
console.log(fB(575));
console.log(fB(49));
console.log(fB(51));
console.log(fB(80));
console.log(fB(375));
console.log(fB(99));
console.log(fB(Infinity));

  • Related