loading...

FizzBuzz in one planet-size JavaScript statement

sergeis profile image Sergei ・1 min read

JavaScript has many tempting features and it is easy to get carried away. And so I have. Here is a FizzBuzz one-liner that uses a whole whack of ES5 and ES6 features:

  • Array.from()
  • Array-like objects
  • Array.assign()
  • map
  • forEach
  • ternary operator
  • truthy and falsy values
  • IIFE
  • and, of course, fat arrow functions
(n=>Array.from({length:n}, (_,i)=>i+1)
.map(e=>({text:e+' ', value: e}))
.map(e=> e.value%3? e: Object.assign(e, {text:e.text+'Fizz'}))
.map(e=> e.value%5? e: {value:e.value, text:e.text+'Buzz'})
.forEach(e=>console.log(e.text)))(100)

Compare this to a purely procedural C-like version:

for (var i = 1; i <= 100; i++) 
  console.log(i+' '+(i%15==0?"FizzBuzz":i%3==0?"Fizz":i%5==0?"Buzz":""));

It takes way less resources and probably runs ten times faster.

The lesson? Sometimes it's best to avoid the frills and stick to the basics.

Discussion

pic
Editor guide