How I solved FizzBuzz in JavaScript

ยท

2 min read

How I solved FizzBuzz in JavaScript

What is fizzbuzz?

FizzBuzz is a simple programming task, commonly used in software developer job interviews, to determine whether the job candidate can write code and to understand how they solve simple problems.

Instructions

Write a program that console logs the number from 1 to n. But for multiples of three print "fizz" instead of the number and for the multiples of five print "buzz". For numbers which are multiples of both three and five

//EXAMPLE
fizzBuzz(5)
//1
//2
//fizz
//4
//buzz

The trick is to firstly check if the number is a multiple of 3 AND 5, if so return 'fizzbuzz'. Else check if number is a multiple of 3, if so return 'fizz'. Finally check if the number is a multiple of 5, if so return 'buzz'. If none of these match return the number

//SOLUTION 1
const fizzBuzz = (n) => {
  //loop n times
  for (let i = 1; i <= n; i++) {
    //check if number is multiple of 3 & 5
    if (i % 3 === 0 && i % 5 === 0) {
      console.log('fizzbuzz')
    } else if (i % 3 === 0) {
      // check if number is multiple of 3
      console.log('fizz')
    } else if (i % 5 === 0) {
      // check if number is multple of 5
      console.log('buzz')
    } else {
      //return number
      console.log(i)
    }
  }
}

After solving the problem in a simple way, I then looked for ways to refactor my original implementation. The first thing that came to mind was taking a don't repeat yourself (DRY) approach using a conditional (ternary) operator:

//SOLUTION 2
const fizzBuzz2 = (n) => {
  for (let i = 1; i <= n; i++)
    console.log((i % 3 ? '' : 'fizz') + (i % 5 ? '' : 'buzz') || i)
}

My next approach was to use recursion. Not sure I would personally use this solution but it was fun to get it working

//SOLUTION 3
const fizzBuzzRecursion = (n) => {
  let counter = 1
  const recursion = (counter) => {
    if (counter > n) return
    const fizz = counter % 3 === 0
    const buzz = counter % 5 === 0
    // console.log(fizz ? (buzz ? 'fizzbuzz' : 'fizz') : buzz ? 'buzz' : counter)
    console.log((fizz ? 'fizz' : '') + (buzz ? 'buzz' : '') || counter)
    recursion(counter + 1)
  }
  recursion(counter)
}
ย