Exercise – Functional FizzBuzz

by iboulder

HTML

<h1>
  FizzBuzz Exercise
</h1>

JavaScript

/**
 * Exercise:
 *
 * FizzBuzz Function
 *
 * Work in the console, or use "console.log()" to output to the console 
 * from the script
 *
 * The FizzBuzz rules...
 *  - for numbers that are a multiple of 3, 
 *    log "Fizz" instead of the number
 *  - for numbers that are a multiple of 5
 *    log "Buzz" instead of the number
 *  - for numbers that are a multiple of both, 
 *    log "FizzBuzz" instead of just Fizz or Buzz
 *
 * 1) Implement the fizzbuzz function:
 *  - It accepts a single number argument
 *  - Outputs the correct response to the console based on the FizzBuzz rules
 *
 * 2) Create a loop that executes your fizzbuzz function for the numbers from 1 to 100
 *
 * 3) BONUS 1 - write tests 
 * use console.assert() to verify your function works as expected
 * ex: console.assert(fizzbuzz(3) === "Fizz"); 
 *
 * 4) BONUS 2 - refactor your function
 *  
 */

function fizzbuzz(n) {
  var strFizzBuzz = '';

  // 1) implement the function
  if (n % 3 === 0) {
    strFizzBuzz = 'Fizz'
  }
  if (n % 5 === 0) {
    strFizzBuzz += 'Buzz'
  }

  return strFizzBuzz
}

// 2) run the function with a loop
for (var x = 100; x > 0; x--) {
  console.log(x + "'s fizzbuzz is " + fizzbuzz(x))
}



// 3) BONUS 1
// use console.assert() to test your function