DEV Community

Cover image for Fizz Buzz Solution JavaScript

Fizz Buzz Solution JavaScript

Hello Dev World Blog on December 28, 2020

If you have been in a developer interview you have probably gotten the fizz buzz problem at some point. Whether it was creating the solution or deb...
Collapse
 
brandonmweaver profile image
Brandon Weaver

Nice solution! if (num % 5 === 0 && num % 3 === 0) can be simplified as if (num % 15 === 0)
Here's a one-liner using ternary operation.

function fizzBuzz(start, end) {
    for (let i = start; i <= end; i++) i % 15 === 0 ? console.log("FizzBuzz") : i % 5 === 0 ? console.log("Buzz") : i % 3 === 0 ? console.log("Fizz") : console.log(i);
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
antogarand profile image
Antony Garand

How about a shorter one liner?

Still using the ternary operators, but using a bit of magic as well.

JavaScript, 62 bytes

for(i=0;++i<101;console.log(i%5?f||i:f+'Buzz'))f=i%3?'':'Fizz'

I think I this is the shortest Javascript solution now.

Collapse
 
hellodevworldblog profile image
Hello Dev World Blog

Ya there are definitely shorter solutions I've seen a couple of one liners most aren't very readable and confuse a lot of devs lol I generally lean more towards readability and this was more to teach newer devs how to break down problems to find their solutions but this is definitely a good solution as well :)

Thread Thread
 
antogarand profile image
Antony Garand

Agreed, which is why I initially posted this comment!

While it is possible to make the code very short, your solution is a lot more legible and maintainable than these one liners.

Collapse
 
hellodevworldblog profile image
Hello Dev World Blog • Edited

I generally lean more towards readability and when its broken out in different lines i find it to be more readable and this was more to teach newer devs how to break down problems to find their solutions but this is definitely a good solution as well :)

Collapse
 
brandonmweaver profile image
Brandon Weaver

Agreed. Your solution is much better, not only for teaching newcomers, but in a real-world environment as well. I wanted to point out that modulus 5 and 3 is the same as modulus 15, and add something different while I was at it.