For my challenge today, I’m going to put a new twist on a classic problem. If you haven’t heard of “Fizzbuzz,” I’m truly honored to be the first person to introduce you two. This most certainly will not be the last time you encounter “the ‘Buzz”.

Fizzbuzz is simple: take in a number and return every number from 1 to that input number, replacing multiples of 3 with “fizz”, multiples of 5 with “buzz”, and multiples of both 3 and 5 with “fizzbuzz”. The console output for fizzbuzz(20) would look like this:

1
2
fizz
4
buzz
fizz
7
8
fizz
buzz
11
fizz
13
14
fizzbuzz
16
17
fizz
19
buzz

A solid solution just handles each situation with an if statement.

function boringFizzBuzz(n) {
  for(var i = 1; i <= n; i++){
    if(i % 3 === 0 && i % 5 === 0){
      console.log("fizzbuzz");
    } else if (i % 3 === 0) {
      console.log("fizz");
    } else if (i % 5 === 0) {
      console.log("buzz");
    } else {
      console.log(i);
    }
  }
}

It works but…

via GIPHY

Let’s spice this function up with some ES6 syntax and ternary operator magic.

const coolFizzBuzz = (num) => {
  for(var i = 1; i <= num; i++){
    console.log((i % 3 === 0 && i % 5 === 0) ?
                  "fizzbuzz" : (i % 5 === 0 ?
                    "buzz" : (i % 3 === 0 ?
                      "fizz" : i)));
  }
}

via GIPHY

Sweet ES6 things used:

1) const. const stands for “constant”. In Javascript, constants are block-scoped, similar to variables that are defined with let (another new ES6 feature). A “block-scoped” variable is only available inside of the curly braces in which it is confined. Additionally, and more importantly, declaring a const variable means that the variable cannot be re-assigned to a different value later on. However, it’s important to note declaring something with const does not necessarily make that thing “immutable”. Check out this blog post for more information on that. Also, MDN docs always keep it real.

2) => Arrow functions! Arrow functions are a shorthand way of declaring anonymous functions. You put the arguments on the left side and then what you want to do with the arguments on the right side. Super handy and concise. In this case, we take advantage of Javascript’s functional programming capabilities (using functions as values) to un-anonymize our arrow function. We give the arrow function a name by storing it in a const called “coolFizzBuzz”. More good stuff about the arrow function here.

Ternary operator usage:

I like ternary operators because they let me condense simple conditional logic flows into one-liners. In this example, the ternary operator line translates to this logic flow: Image and video hosting by TinyPic

All in one line (kind of). I broke it up into multiple lines because nobody likes sideways scrolling. Anyways, pretty cool, huh?

Please don’t hesitate to email or tweet at me with questions or suggestions - contact info in the footer.

Happy Friday - have a great weekend. Vince out.