Javascript FizzBuzz problem

This is the classic Javascript FizzBuzz problem where the task is to loop through n numbers and print “fizz” for multiples of 3, “buzz” for multiples of 5 and “fizzbuzz” for multiples of 3 and 5 (i.e. 15).

This is a rather simple problem.  The main thing is to test your knowledge of the modulo “%” operator.  It is a unique operator in Javascript that tells you the remainder of a division operation.  Example 9 % 3 = 0; 10 % 3 = 1.  Three goes into 9 three times with 0 remainder.  Three goes into 10 three times with a remainder of 1.

function fizzBuzz(n) {

   for (let i = 1; i<= n; i++) {
      // is the number a multiple of 3 && 5 = 15
      if (i % 15 === 0) {
         console.log('fizzbuzz');
      // is the number a multiple of 5 
      } else if (i % 5 === 0) {
         console.log('buzz');
      // is the number a multiple of 3 
      } else if (i % 3 === 0) {
         console.log('fizz');
      // if not a multiple of 3,5 or 15, print the number   
      } else {
         console.log(i);
      }
   }
};

 

Leave a Reply

Your email address will not be published. Required fields are marked *