FizzBuzz: THE Question in coding

Fizzwha?

If you have spent any time at all looking for coding jobs you have at least heard about FizzBuzz in passing. The coding problem has been used in interviews for years to determine if a candidate knows how to write code. It goes like this:

Initial Solve

As with most coding problems its best to start with some notes to get an idea of what needs to happen

//We need to iterate through an array of numbers from 1 to 100
//Numbers divisible by 3 will print the word "Fizz"
//Numbers divisible by 5 will print the word "Buzz"
//Numbers divisible by both 3 and 5 will print the word "FizzBuzz"
//Numbers not divisible by either will be printed as they are
for (var i=1; i <= 100; i++)
for (var i=1; i <= 100; 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)
}
}

Another Way

I have poured through different solutions for FizzBuzz and have been blown away with the variety. One of the coolest (and faster) ways to solve is using a ternary operator. Let take a look at the example:

function fBTernary() {
for (var i = 1; i <= 100; i++) {
var f = i % 3 == 0, b = i % 5 == 0;
console.log(f ? b ? “FizzBuzz” : “Fizz” : b ? “Buzz” : i);
}
}

Buzz Off

FizzBuzz may be a bit antiquated and over discussed by now but I think it is a great starting point for new developers to practice thinking programatically. As mentioned before, there are more ways to solve this than I would care to count. Try it for yourself and see if you can put your own spin on this time-honored problem.

I love traveling, music, and movies.