Search code examples
javascriptfizzbuzz

FizzBuzz: 15 shows Fizz but no Buzz on newline. Why? Just need clarification


Just trying to understand on why Buzz doesn't appear in the newline after Fizz for 15.

Trying to learn JavaScript from Eloquent Javascript and just got into doing the FizzBuzz exercise. Note that I've included a commented out solution where it does work (although not elegantly) but the thing I've notice that some solutions searched online show their 15 appearing with Fizz but Buzz is on a newline while my solution (which is not commented out) only shows Fizz.

Can anyone explain to me why does it do this? Just curious. The only thing I've noticed is when I use

if ((int%3 == 0) && (int%5 == 0))

either at the end or the beginning of the block is when the changes are visible.

Note:

I'm not asking for solutions. I just want an explanation to my question above. The commented solution does give me FizzBuzz for 15. Please do not misunderstand and thank you for taking your time to answer this.

My solution:

for(let int = 1; int <= 100; int++){
  if(int%3 == 0){
    console.log('Fizz');
  }
  else if(int%5 == 0){
    console.log('Buzz');
  }
  else if ((int%3 == 0) && (int%5 == 0)){
    console.log('Fizz'+'Buzz');
  }
  /*if ((int%3 == 0) && (int%5 == 0)){
    console.log('Fizz'+'Buzz');
  }
  else if(int%3 == 0){
    console.log('Fizz');
  }
  else if(int%5 == 0){
    console.log('Buzz');
  }*/

  else{    
    console.log(int);
  }
}

Solution

  • In you solution, the following block is dead code :

    else if ((int%3 == 0) && (int%5 == 0)){
        console.log('Fizz'+'Buzz');
    

    This console.log('Fizz'+'Buzz') can never be reached because ((int%3 == 0) && (int%5 == 0)) would mean that (int%3 == 0) and so the first if is executed. Because of the meaning of else if, this later code block is never reached.

    So to answer directly :

    show their 15 appearing with Fizz but Buzz is on a newline

    This probably is a coding error as FizzBuzz usually requires writing "Fizz Buzz" on a single line for 15. I would guess they did not use any "else if" - which you did.

    my solution (which is not commented out) only shows Fizz. Can anyone explain to me why does it do this.

    Because else if blocks order is important, and you chose the wrong one.