Notes

Fizz Buzz

Edit on GitHub

Algorithms
2 minutes
  • A function that takes in a parameter as number, let’s call it num
  • It will log out to the console every number from 1 to num
  • For each number, if the number is divisable by 3, it’ll output the word Fizz instead of the number.
  • For each number, if the number is divisable by 5, it’ll output the word Buzz instead of the number.
  • For each number, if the number is divisable by both 3 and 5, it’ll output the word FizzBuzz instead of the number.

Print all numbers from 1 till num

Using a for loop

1// print all numbers from 1 till `num`
2for (i = 1; i <= num; i++) {
3  console.info(i)
4}

Solution

 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)