JS Tertiary Operator- FizzBuzz Solution

I decided to refactor my fizzbuzz solution in Javascript. This week we are delving into this programming language and I am enjoying it.

My goal was to see how much I could refactor my fizzbuzz code below.


function fizzBuzz(n) {
  if(n % 15 == 0) {
    return "fizzbuzz";
  } else if(n% 3 == 0) {
    return "fizz";
  } else if(n % 5 == 0) {
    return "buzz";
  } else {
    return n;
  }
}

So I used the tertiary operator for this. It looks like this:


test ? expression1 : expression2

Basically, this returns one of two expressions depending on a condition. It will return expression1 is the test turns out to be true or expression2 otherwise.

example:


2 > 3 ? "this is true" : "this is false"

The above code would return “this is false”

Having the tertiary operator in mind I went on to solve fizzbuzz with it and I got this.


function fizzBuzz(num){
(num % 15 == 0) ? console.log("fizzbuzz"):(num % 5 == 0) ? console.log("buzz") : (num % 3 == 0) ? console.log("fizz") : console.log(num)
}

Notice the nested tertiary operators.
First this is the test


(num % 15 == 0) 

if this is true I want to return


 console.log("fizzbuzz")

But if this is false then I want to go to the nested tertiary operator:


(num % 5 == 0) ? console.log("buzz") : (num % 3 == 0) ? console.log("fizz") : console.log(num)

Here, the program will look whether num is modulo of 5. If it is, then it will print “buzz”. If it is not, it will evaluate another tertiary operator. This operator will check if num now is modulo of 3. It will print “fizz” if it is, or print num (itself) if it is not.

And this is how I reduced my fizzbuzz function from 10 lines to 3.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s