Search code examples
javascriptfizzbuzz

I "solved" FizzBuzz, but I don't understand why it's working


I'm completely green. Just started reading Eloquent JavaScript, and Chapter 2 gets into some exercises.

Apparently the "FizzBuzz" problem needs no introduction. I spent the better part of an hour giving it an honest go, trying different approaches.

Finally arrived at a not-so-eloquent solution. But as I look at it, I don't understand how it works:

var x = 1
while (x <= 20){
  if (x % 5 == 0 && x % 5 == 0){
    console.log("FizzBuzz");
  }
  else if (x % 5 == 0){
    console.log("Buzz");
  }
  else if (x % 3 == 0){
    console.log("Fizz");
  }
  else
    console.log(x);
    x++;
}

So, with my current understanding: I would expect this script to count up to 3 for the first "Fizz", then get stuck in an infinite loop.

Obviously I'm understanding this wrong. How is it that the script moves past this onto '4'?

Thanks for reading.


Solution

  • If you format it correctly it becomes apparent.

    var x = 1
    while (x <= 20){
      if (x % 5 == 0 && x % 3 == 0){
        console.log("FizzBuzz");
      }
      else if (x % 5 == 0){
        console.log("Buzz");
      }
      else if (x % 3 == 0){
        console.log("Fizz");
      }
      else
        console.log(x);
      x++;
    }
    

    That is, x++ gets executed independently of the conditionals, because the else clause has no braces, so it only considers one statement (that is the console.log)

    I also corrected the error you had in your first condition (you checked x%5 twice instead of checking for x%3).