Monthly Archives: January 2014

Smallest JavaScript FizzBuzz solution possible?

Maybe you have seen this kind of viral picture about a guy who gets asked to program FizzBuzz in a job interview.

My friend and I tried to make the smallest possible JavaScript FizzBuzz solution possible. Here were our requirements:

  • Print numbers from 1 to 100
  • If a number is divisible by 3, print “Fizz” instead
  • If a number is divisible by 5, print “Buzz” instead
  • If a number is divisible by 3 and 5, print “FizzBuzz” instead
  • Print using console.log
  • Pure JavaScript only

First Try (101 characters)

for(n=1;n<=100;++n){s="";if(!(n%3))s="Fizz";if(!(n%5))s+="Buzz";else if(n%3&&n%5)s=n;console.log(s);}

Uses a simple if-else clause and appends the strings "Fizz" and "Buzz", so we don't need an extra "FizzBuzz" in our code.

Second Try (69 characters)


30 characters shorter! This uses some neat tricks in JavaScript. console.log logs the return value of a || operator. The || operator evaluates the left -and right-handed side of it and returns the first true value. An empty string is considered false in JavaScript, therefore it would print the number if the number is not divisible.

Third Try (64 characters)


Have a look at the for-loop on this one. Using the pre-increment operator ++ we don't need the last argument in our for-loop. We were also able to remove the parentheses in the ternary statements.

Can you make it even shorter? Reply down below!