Fizz Buzz in JavaScript

Fizz Buzz in JavaScript

To understand JavaScript
all I need is the console, a variable
or may be a loop
......................................................
To retain my sanity I’ve leave all of its other
functions to you

As a newbie I often skip any video or article I see algorithm in its title. My excuse is that I’m already struggling to understand what the “return” in a function means. I’d rather focus on that than to add another wahala to my already long list of topics-to-learn on my map. But with everything programming you’ll often ran into problems you’re not ready for and that’s exactly what happened to me.

ENTER: FIZZ BUZZ

The instruction was clear, I swear!
“Output numbers 1- 100 except for the following statements;
If the number is divisible by 3 print “Fizz”,
If the number is divisible by 5 print “Buzz”, and
If the number is divisible by both 3 and 5 print “Fizz Buzz”

What could go wrong right, the code to write is so sweet I started it with a pseudo

PSEUDO CODE

(For number 1 – 100)
If it’s divisible by 3
Console.log(“Fizz”);
Else if it’s divisible by 5
Console.log(“Buzz”);
Else if it’s divisible by 3 && 5
Console.log(“Fizz Buzz”);
Gerrit!

THE CODE

fizzBuzz.png

OUTPUT

Fizz: I feel like driving my fist into this screen
Buzz: I feel like blowing up my brain, mans can be this dumb,
..............................................................................................
My brain; “I thought you said we eating this like pie?!!!”

fizzresults.png

As you can see from the output above fizz was printed out, buzz was also printed out but what about fizz Buzz? At first I thought I’ve probably messed up the "if else statement"; it is typical of those just coming out of tutorial hell. So I re-checked the modules %, strict equality === and the && operators. they’re all ok! 😱

ENTER: Algorithm & Data structure

Apparently Fizz Buzz is a common problem given in interviews, because it requires you to not only think about the code but its structure, you're to solve it from the most specific condition to the more generic ones.

fizzBuzz2.png

In our case we checked for individual numbers first, hence we ran into a bug, so rather we should've put the most specific condition at the top. We should first check for condition that will print out Fizz Buzz, if it’s not met it will check for the other conditions. And that is how I met your mom DSA, unprepared but fun after uncle Google held my hands through it.

fizzbussresults.png

I hope you enjoy reading this not so perfect mix of poetry and code, till next time keep coding. Salam!