DEV Community

Discussion on: Fizz Buzz Solution JavaScript

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.