1
      for (let number = 0; number <= 100; number++ ) {
            let output = ""
            if (number % 3 == 0) output += "Fizz"
            if (number % 5 == 0) output += "buzz"
            console.log(output || number)
  
            }

I understand why it finds the modulo for 3 and 5. But why does this also find the modulo for 15? (The question asks to also find the numbers that are divisible by 3 and 5 and print "Fizzbuzz").

I was able to solve the question in a different manner and was offered this as one of the ideal solutions.

Is the += after the output somehow multiplying the other two remainders?

  • 1
    In general, if you want to learn how/why a piece of code works, then load it in a debugger and step through it line by line. Chrome has a built-in Javascript debugger that's pretty good! – Jorn Oct 18 '21 at 15:05
  • Thank you jorn! I think I understand each individual piece but I am drawing a blank on how this reaches 3 and 5 modulos combined. I know it is something simple or right in front of my eyes but I just can't get it. – DanteArceneaux Oct 18 '21 at 15:09
  • 1
    Note that there's no `else` before the second `if` – Jorn Oct 18 '21 at 15:10

2 Answers2

3

If your question is about the use of +=, then it is a short form of writing output=output+"Fizz". Hence instead of writing the above one we can simply write output+="Fizz"

frippe
  • 1,329
  • 1
  • 8
  • 15
Ruthvik
  • 790
  • 5
  • 28
  • Why does this also output the modulo for 3 and 5 together? It seems to me I should have to write a third if loop ( number % 5 == 0 && number % 3 == 0) output += "Fizzbuzz – DanteArceneaux Oct 18 '21 at 15:02
  • @DanteArceneaux: no, you don't need to, because these ifs are independent / not mutually exclusive. That is, number 15 will trigger both checks for 3 and 5. – Sergio Tulentsev Oct 18 '21 at 15:06
  • This program actually checks if it is divisible by 3 first, If yes then add Fizz then checks divisibility for 5, if yes then add buzz – Ruthvik Oct 18 '21 at 15:10
  • Thank you so much guys! Would have taken me forever to figure out on my own. I understand now – DanteArceneaux Oct 18 '21 at 15:15
2

The answer to my question is that the program runs both checks independently. When it reaches 15 (or any other number divisible by both 3 and 5), it will simply add "Fizz" and "buzz" together to create "Fizzbuzz".