Skip to content

Instantly share code, notes, and snippets.

@jaysonrowe
Created January 11, 2012 01:39
Show Gist options
  • Save jaysonrowe/1592432 to your computer and use it in GitHub Desktop.
Save jaysonrowe/1592432 to your computer and use it in GitHub Desktop.
FizzBuzz JavaScript solution
for (var i=1; i <= 20; i++)
{
if (i % 15 == 0)
console.log("FizzBuzz");
else if (i % 3 == 0)
console.log("Fizz");
else if (i % 5 == 0)
console.log("Buzz");
else
console.log(i);
}
@Mike-UU07
Copy link

const FizzBuzz = (range) => {
for (let i = 0; i <= range; i++) {
if (i === 0) {
console.log(i)
} else if (i % 15 === 0) {
console.log("Fizz Buzz")
} else if (i % 3 === 0) {
console.log("Buzz")
} else if (i % 5 === 0) {
console.log('Fizz')
} else {
console.log(i)
}
}
}

a quick fizzbuzz function where you can choose how many # you want to console.log
you can invoke the function by FizzBuzz() then inside the brackets how many numbers you want

@cyber-amr
Copy link

Short and flexible

for(i=0;++i<101;)console.log([3,5].reduce((t,v,j)=>i%v?t+'':t+['Fizz','Buzz'][j],'')||i) // 88 characters
for(i=0;++i<101;)console.log([3,5,7,11].reduce((t,v,j)=>i%v?t+'':t+['Fizz','Buzz','Fuzz','Bizz'][j],'')||i)

@macder
Copy link

macder commented Aug 25, 2022

The idea is so that it's readable and maintainable

Clever one liners only come back to haunt you, or the next poor guy working on the code.

Convolution indicates an inadequacy with naming things, not coding prowess. Any developer can forgo variables for expressions, use anonymous functions, and cram everything together without formatting. The responsible ones realize the cost heavily outweighs some weird belief that a few less lines is somehow a benefit.

A declarative approach will give you an edge, not some one liner that causes cognitive overload, making the next change request a fun time...

const isFactorOf = (divisor) => (dividend) => !(dividend % divisor)
const nonZeroIndex = (mapFn) => (index) => mapFn(index + 1)
const makeArrayOf = (fn) => (length) =>
  [...Array(length).keys()].map((index) => fn(index))

const fizzBuzzOrNum = (num) =>
  isFactorOf(15)(num) && "fizzbuzz" ||
  isFactorOf(3)(num) && "fizz" ||
  isFactorOf(5)(num) && "buzz"||
  num

const fizzBuzz = makeArrayOf(nonZeroIndex(fizzBuzzOrNum))

console.log(fizzBuzz(100))

OR the cruel version of the same code, in case you want your future self and co-workers hating you

// only difference from code above is unformatted without variables for expressions to make it look 1337. 

console.log(
  [...Array(100).keys()].map(i=>(i=>!(i%15)&&"FizzBuzz"||!(i%3)&&"Fizz"||!(i%5)&&"Buzz"||i)(i+1))
)

// Gee, thanks for minifying the code so that the build script has less work...

@ihtisham-Ullah
Copy link

function fizzBuzz(n) {
for(let i=1; i<=n; i++)
{

if((i%3==0) && (i%5==0))
{
console.log("FizzBuzz");
}

if((i%3==0) && (i%5!==0))
{
console.log("Fizz");
}

if((i%5==0) && (i%3!==0))
{
console.log("Buzz");
}

if((i%3!==0) && (i%5!==0))
{
console.log(i);
}

}

}

@lpmagdiel
Copy link

const fizzBuzz = n => (n%15? (n%3? (n%5? (n%7? '' : 'woff') :'buzz') : 'fizz') : 'fizzbuzz') || n;

@NayanaKalhane
Copy link

public class Solution {

public static void main(String[] args) throws IOException {
    int n = 0;
    
    for (int i = 1; i <= n; i++){
        if(i % 3 == 0 && i % 5 == 0)
        System.out.println("FizzBuzz");
    else if (i % 3 == 0 && i % 5 != 0)
        System.out.println("Fizz");
    else if (i % 5 == 0 && i % 3 != 0)
        System.out.println("Buzz");
    else
        System.out.println(i);  
    }
}

}

@paschalyn1
Copy link

function fizzBuzz(arr){
let len = arr.length;
for(let i = 0; i < len; i++){
//multiples of 3 and 5
if(arr[i] % 3 === 0 && arr[i] % 5 === 0){
arr[i] = "FizzBuzz";
}
//multiples of 3 but not multiples of 5
if(arr[i] % 3 === 0 && arr[i] % 5 !== 0){
arr[i] = "Fizz";
}
//multiples of 5 but not multiples of 3
if(arr[i] % 3 !== 0 && arr[i] % 5 === 0){
arr[i] = "Buzz";
}
}
return arr;
}

//call the function torender result.
console.log(fizzBuzz([1, 2, 3,4,5,6,7,8,9,10,11,12,13,14,15]))

@ahmadad62
Copy link

ahmadad62 commented Oct 6, 2022

Switch Case Solution
`

for (var i = 1; i <= 100; i++) {
switch (true) {
case i % 5 == 0 && i % 3 == 0:
console.log("FizzBuzz");
break;
case i % 5 == 0 && i % 3 != 0:
console.log("Buzz");
break;
case i % 3 == 0 && i % 5 != 0:
console.log("Fizz");
break;
default:
console.log(i);
break;
}
}`

@Metteus96
Copy link

for (num = 1; num < 101; num++) {
resultado = "";
if (num % 3 === 0) {
resultado = "Fizz";
}
if (num % 5 === 0) {
resultado = resultado + "Buzz";
}
if (resultado === "") {
resultado = num;
};
console.log(resultado);
};

@Khris234
Copy link

Khris234 commented Dec 7, 2022

omo..!!!....HEADache don dey worry me...

@Iwumezie-pamela
Copy link

Iwumezie-pamela commented Dec 21, 2022

for (let i=1; i <=100; i++){
   if(i  %  3 === 0  && 1 % 5 === 0){
    console.log('FizzBuzz')
  }else if(i  %  3 === 0){
    console.log('Fizz')
  }else if(i % 5 == 0){
    console.log('Buzz')
  }else{
   console.log(i)
  }
}

@ayodejii
Copy link

short modern js solution

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

using short synthax is fun and games until you want to read the code.

@0xadada
Copy link

0xadada commented Jan 22, 2023

short modern js solution

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

using short synthax is fun and games until you want to read the code.

We're all here for fun and games, none of this is production code bruh

@pickworth
Copy link

We're all here for fun and games, none of this is production code bruh

Agreed. If you need to adopt FizzBuzz for production use, you are in the wrong place. FizzBuzz enterprise edition is recommended for these use cases https://github.com/EnterpriseQualityCoding/FizzBuzzEnterpriseEdition

@b0yblake
Copy link

let i = 1;
while(i <= 100) {
console.log((${i%3===0?'Fizz':''}${i%5===0?'Buzz':''}) || i)
i++;
}``

@b0yblake
Copy link

b0yblake commented May 31, 2023

Using currying is highly technical but for some reason, I think is not more reliable than one-line code (It divides so many fn to solved). I just think we can use HOC or using closures to limit the context.

@essenmitsosse
Copy link

essenmitsosse commented May 31, 2023

If you want fun and games:

new Array(100)
    .fill()
    .map((_,i) => `${i%3===0?'Fizz':''}${i%5===0?'Buzz':''}`)
    .forEach(console.log)

or a little more testable

const fizzbuzz = (_,i) => `${i%3===0?'Fizz':''}${i%5===0?'Buzz':''}`

new Array(10).fill().map(fizzbuzz).forEach(console.log)

@Megafry
Copy link

Megafry commented Jun 1, 2023

@essenmitsosse

The use of forEach is not necessary here since map already traverses the array.
But I like how you used fill

new Array(100).fill().forEach((_,i) => {
    i++
    console.log((`${i%3===0?'Fizz':''}${i%5===0?'Buzz':''}`) || i)
})

@essenmitsosse
Copy link

@Megafry If you want fizzbuzz to be side-effect free, it still makes sense to separate the two. Also, I usually wouldn't expect map to have a side effect — that's what forEach is for. It is an additional traversal, but in most cases, the gain in clarity should outweigh the performance hit.

@mortocks
Copy link

Not the smallest / most elegant solution but when that pesky product manager wants to add "boop" on 7 it won't require a refactor

const fizzBuzz = (duration = 100) => Array(duration).fill().map((_, i) => {
  i++
  const subs = new Map([[15, "Fizzbuzz"], [3, "Fizz"], [5, "Buzz"] ])
  const match = Array.from(subs.keys()).find(k => i % k === 0)
  return match ? `${subs.get(match)}` : `${i}`;
})

console.log(fizzBuzz())

@nehalkadyan
Copy link

for (var i = 1; i <= 100; i++) {
switch (true) {
case i % 5 == 0 && i % 3 == 0:
console.log("FizzBuzz");
break;
case i % 5 == 0 && i % 3 != 0:
console.log("Buzz");
break;
case i % 3 == 0 && i % 5 != 0:
console.log("Fizz");
break;
default:
console.log(i);
break;
}
}

Thanks man, was looking for switch case implementation on this one.

@persianturtle
Copy link

for (let i = 1; i <= 100; i++) {
  const fizz = i % 3 === 0 ? "Fizz" : ""
  const buzz = i % 5 === 0 ? "Buzz" : ""
  console.log(`${fizz}${buzz}` || i)
}

@Wlad2000
Copy link

Wlad2000 commented Feb 1, 2024

const fizzBuzz = (num, rules) => {
  const result = [];
  for (let i = 1; i <= num; i++) {
    result.push(applyRules(i, rules));
  }
  return result;
};

const applyRules = (num, rules) => {
  const output = rules.reduce((result, rule) => {
    if (rule.condition(num)) {
      result += rule.output;
    }
    return result;
  }, '');

  return output || num;
};
 // Example usage:
  const isMultipleOf = (n) => (num) => num % n === 0;
  const rules = [
    { condition: isMultipleOf(3), output: 'Fizz' },
    { condition: isMultipleOf(5), output: 'Buzz' },
  ];
    const resultArray = fizzBuzz(15, rules);
    console.log(resultArray);

@GTRshaoran
Copy link

//para imprimir en la página web const n= window.prompt("Ingrese un número: "); for(i=1; i<=n; i++) if(i%3==0 && i%5==0){ console.log("FizzBuzz\n"); } else if(i%3==0 && i%5!=0){ console.log("Fizz\n"); } else if(i%3!=0 && i%5==0){ console.log("Buzz\n"); } else{ console.log(i\n); }

@iuliaGrig
Copy link

Which way would be "better regarded" as a best answer, by using for loops or by using .forEach() and .map()? Or it really does not matter as long as the program executes what is expected of it? Cheers

@essenmitsosse
Copy link

@iuliaGrig The answer is: It depends.

In this example, it's so simple that it doesn't matter for most intents and purposes. For more complex examples a rule of thumb could be:

  • .forEach and .map are generally more readable (even though plenty of people already might disagree). .forEach should be used if there are side-effects to the function (like console.log), .map must be used if you want to create a new list (.forEach doesn't return anything)
  • for-loops are generally more performant, even though the difference only really matters for very large lists

@taosx
Copy link

taosx commented Oct 9, 2024

A v8 optimized version (I'd be quite surprised if it can be made faster by keeping the same signature):

function fizzBuzz(limit = 100) {
  var result = new Array(limit),
    f = "Fizz",
    b = "Buzz",
    fb = "FizzBuzz",
    i = 0;

  for (; i + 15 <= limit; i += 15) {
    result[i] = i + 1;
    result[i + 1] = i + 2;
    result[i + 2] = f;
    result[i + 3] = i + 4;
    result[i + 4] = b;
    result[i + 5] = f;
    result[i + 6] = i + 7;
    result[i + 7] = i + 8;
    result[i + 8] = f;
    result[i + 9] = b;
    result[i + 10] = i + 11;
    result[i + 11] = f;
    result[i + 12] = i + 13;
    result[i + 13] = i + 14;
    result[i + 14] = fb;
  }

  var pattern = [0, 0, f, 0, b, f, 0, 0, f, b, 0, f, 0, 0, fb];
  for (; i < limit; i++) result[i] = pattern[i % 15] || i + 1;

  return result;
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment