DEV Community

Terry Threatt
Terry Threatt

Posted on • Updated on

FizzBuzz for Javascript

New developers will surely see this problem show up in technical interviews. FizzBuzz is a classic technical interview questions to find out if you are familiar with solving programming challenges.

FizzBuzz setup:

Create a solution that prints the number 1 through 100. Print "Fizz" for numbers that have a multiple of 3. Print "Fizz" for numbers that have a multiple of 5. Print "FizzBuzz" for numbers that have a multiple of both 3 and 5.

FizzBuzz solution: (There's many ways to solve this problem)

for (let i = 1; i <= 100; i++) {
    // Finding multiples of 3 and 5
    if (i % 3 === 0 && i % 5 === 0) {
      console.log('FizzBuzz');
    } else if (i % 3 === 0) {
      // Finding multiples of 3
      console.log('Fizz');
    } else if (i % 5 === 0) {
      // Finding multiples of 5
      console.log('Buzz');
    } else {
      console.log(i);
    }
  }
Enter fullscreen mode Exit fullscreen mode

Top comments (6)

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited
console.log([...Array(100)].map((e,i)=>(++i%3?'':'Fizz')+(i%5?'':'Buzz')||i).join("\n"))
Enter fullscreen mode Exit fullscreen mode
Collapse
 
peerreynders profile image
peerreynders • Edited

Seems like an opportunity for Array.from()

const select = ([n, word]) => word || n.toString();
const make = (divisor, text) => (v) =>
  v[0] % divisor === 0 ? [v[0], v[1] + text] : v;
const fizz = make(3, 'Fizz');
const buzz = make(5, 'Buzz');
const fizzBuzz = (_v, i) => select(buzz(fizz([i + 1, ''])));
console.log(Array.from({ length: 100 }, fizzBuzz).join('\n'));
Enter fullscreen mode Exit fullscreen mode
Collapse
 
grahamthedev profile image
GrahamTheDev • Edited

Minor mistake - this will print all the numbers to 101 not to 100! Still gets a ❤ though!

Collapse
 
jonrandy profile image
Jon Randy 🎖️
const fizzBuzz = x=>({1:x,6:f="Fizz",10:b="Buzz",0:f+b}[x**4%15])
Enter fullscreen mode Exit fullscreen mode
Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited
const fizzbuzz = x=>[x,f='Fizz',b='Buzz',f+b][!(x%3)|!(x%5)<<1]
Enter fullscreen mode Exit fullscreen mode
Collapse
 
mohit789 profile image
mohit vishwakarma

👍