num
num
Fizz
instead of the number.Buzz
instead of the number.FizzBuzz
instead of the number.num
Using a for
loop
1// print all numbers from 1 till `num`
2for (i = 1; i <= num; i++) {
3 console.info(i)
4}
1function fizzbuzz (num) {
2 // print all numbers from 1 till `num`
3 for (i = 1; i <= num; i++) {
4
5 // if number divisible by both 3 and 5, print FizzBuzz
6 if ((i % 3 === 0) && (i % 5 === 0)) {
7 console.info(`FizzBuzz`)
8 }
9
10 // if number divisible by 3, print Fizz
11 else if (i % 3 === 0) {
12 console.info(`Fizz`)
13 }
14
15 // if number divisible by 5, print Buzz
16 else if (i % 5 === 0) {
17 console.info(`Buzz`)
18 }
19
20 // if not divisible by 3 or 5, just print the number
21 else {
22 console.info(i)
23 }
24 }
25}
26
27fizzbuzz(39)
We know that a number that is both divisibleby 3 and 5 is also divisible by 15. So
1if ((i % 3 === 0) && (i % 5 === 0))
is the same as
1if (i % 15 === 0)