The Ultimate Guide to JavaScript Algorithms - Lesson #21

JavaScript Algorithms: The Classic Fizzbuzz

The Fizzbuzz Challenge is one of the most popular coding interview questions in the world of software development.

Like many who have encountered it before, we will logically think through the problem and come up with a fitting solution.

Let's dive right in!

You should already have your development environment setup for this course. Open the cloned repository and inside the Beginner folder, navigate to the fizzBuzz folder. Our work for this challenge will be done in here. Make sure to follow along in the index-START.js file.

Write a program that prints the numbers from 1 to n. But for multiples of three print “fizz” instead of the number and for the multiples of five print “buzz”. For numbers which are multiples of both three and five print “fizzbuzz”. E.g


prints out:


Pretty simple, yeah?

From the challenge statement, we notice that the function is expected to have just one parameter i.e the maximum limit(n).

For each number between 1 and n, we are expected to print out the value except it matches any of the following conditions:

  • If the number is a multiple of 3, we print out "fizz"
  • If it is a multiple of 5, we print out "buzz"
  • If it is a multiple of both 3 and 5, we print out "fizzbuzz".

To understand the challenge better, let's do some quick math.

A multiple is a number that may be divided by another number a certain number of times without a remainder. i.e 6 is a multiple of 3 because it can be divided by 3 without a remainder.

With this in mind, the conditions could be understood to mean:

  • If the number can be divided by 3 without remainder, print out "fizz"
  • If it can be divided by 5 without remainder, print out "buzz"
  • And if it can be divided by both 3 & 5 without remainder, print out "fizzbuzz".

Every number that is a multiple of both 3 and 5 is a multiple of 3 times 5 (i.e 15). This means that the last condition could be understood to mean that if the number can be divided by 15 without remainder, we print out fizzbuzz.

Enough talk! Let's code!

The fizzbuzz challenge is a pretty direct challenge, so we will examine just one way to solve it. Other solutions that may exist are simply minimal variations of what we shall now consider.

In the solution below, we use a for-loop to iterate from 1 to n while using an if statement to perform the desired checks.

function fizzBuzz(n) {
    for (let i = 1; i <= n; i++) {
        // Is a multiple of 3 and 5?
        if (i % 15 === 0) {
        } else if (i % 3 === 0) {
            // Is a multiple of 3?
        } else if (i % 5 === 0) {
            // Is a multiple of 5?
        } else {
            // Is neither of the above?

We start our iteration with the iterator set to an initial value of i. Then we continuously increment it by 1 until it is lesser than or equal to n.

For each iteration we use a set of if, else if & else statements to check if the number is first a multiple of 15, then 3 and 5 subsequently. In each case,we log (print out) the appropriate message to the console.

If none of the conditions are met, it defaults to the else statement which logs the number as it is to the console.

See? That was simple!

Using ES6, and ternary operators, we can reduce the procedural implementation above to what we have below without messing with the accuracy.

A ternary operator in JavaScript is used as as shortcut for writing an if statement. It accepts 3 parameters in this format:

condition ? exprT : exprF 

Applying this to the solution above, we have:

function fizzBuzz(n) {
    for (let i = 0; i < n;)
        console.log((++i % 3 ? '' : 'fizz') + (i % 5 ? '' : 'buzz') || i)

Isn't that elegant? Doesn't look very explanatory though. Let's try to make some sense of it by breaking it up into smaller chunks.

Looping from 1-n We use a for-loop to iterate from 0 to n as shown in the code below:

for (let i = 0; i < n;)
//some other code

For-loop statements usually follow this syntax:

for ([initialization]; [condition]; [final-expression])

However, unlike our conventional for-loop statements, we do not have a final expression statement which is to be executed at the end of each iteration. You'll see why shortly.

Conditionals with Ternary Operators

console.log((++i % 3 ? '' : 'fizz') + (i % 5 ? '' : 'buzz') || i)

The complex console.log statement above makes use of ternary operators to evaluate the appropriate response for each case. Let's analyse them individually.

(++i % 3 ? '' : 'fizz')

Notice that we use the ++ (incrementing) operator to increase the value of i. This serves as a replacement for final expression in our for-loop. When the operator comes before a variable, it means that the variable is incremented before being used. Thus, since our starting value of i is 0, on the first iteration it is incremented to 1 before any evaluation begins. Same goes for subsequent iterations.

The remainder operator % , returns the remainder left over when one number is divided by another number. It always takes the sign of the number that is divided.

We use this operator to check if i is completely divisible by 3. If it is we return fizz , else we return an empty string.

The next statement there is :

(i % 5 ? '' : 'buzz')

It is similar to what we have above, except that we don't have to increment i anymore. We simply check if it is completely divisible by 5. If it is, we return buzz and if it isn't we return an empty string.

Next, we use the logical OR operator to specify a final case.

The logical OR operator will return true if at least one operand is true.

|| i

We use this operator above to specify that if every tests carried out before evaluated to a falsy value(e.g an empty string), we simply return the value of i.

You see! It's a lot simpler than you may have expected.

Summarily, what the code above does is:

Is i completely divisible by 3, if yes print “fizz” else print ""+Is i completely divisible by 5, if yes print “buzz”, else print ""ORSince i is neither divisible by 3 or 5, simply print out i

Thus, in a case where i is divisible by both 3 and 5, the first two checks pass and we have fizz+buzz (i.e fizzbuzz) and the last case is ignored since the first two instances didn't return falsy values.

Gloves off! Nicely done. 👍🏾

Since we have considered only one solution, we would simply test it's correctness with jest. To run the tests, execute the following command from your terminal:

We pass all tests. 💯

This challenge is mostly encountered as a coding interview question. However, the techniques used and the concepts highlighted are valid for executing mathematical computations in real world applications.

We have now learnt to implement the classic fizzbuzz algorithm in JavaScript by examining a procedural approach and a more condensed solution.

This challenge marks the first of our mathematical algorithms, and signals more to come. We definitely would have fun with them, but most importantly, we get to sharpen our mathematical understanding alongside our programming skills.

How exciting!

To learn more about the techniques and concepts applied above, you may use the links below:

See you in the next one!✌🏿

Want to improve your coding and design skills?

I'm continually researching the best practices and tools for coding.
Join 50,000+ developers looking to make cool stuff.

We value your privacy. 1-click unsubscribe.


What did you think of the article? Let us know!
(these comments are powered by GitHub issues and use 0 trackers)