Expandable fizz buzz javascript I've been learning JavaScript for a few weeks and thought to give the ol' fizzbuzz another try. My goal was for expandability. In other words, I wanted to be able to add more keywords without having to rewrite parts of the code. 

I tried to add comments to clarify some of the more unorthodox parts of my code. However, I still feel my code is somewhat terse... Is it better to just write the plain old for-loops for readability and support of IE?

I also opted to check if the string existed instead of checking if the length was greater than zero. Are there any pitfalls I might fall into just checking for existence? I mean if my key were false it would fail, however that would never happen as all the key values are strings anyways. 



function fizzBuzz(divisors = {
        fizz: 3,
        buzz: 5
    }, maxNumber = 100) {
        /* Takes in a object of divisors of the form
           divisors = {
               name: value,
           };
           and an integer. Loops through the list if number below or equal
           maxNumber. If a number is divisible by one of the values, print the name.
          */
        for (var num = 1; num &lt;= maxNumber; num++) {
            var str = "";
            // Loops through the keys of the divisors
            Object.keys(divisors).forEach(function(key)  {
                // Ternary expression, if divisible append key else do nothing
                str += num % divisors[key] == 0 ? key : '';
            });
            // If anything got appended print string else num
            console.log(str ? str : num)
        }
    }
    
    fizzBuzz()
What if I wanted every 7 number to also add fizz, so 105 would be fizzbuzzfizz? You can't do that in your code, since you are using the string as the (unique) key and the number as the value. Instead, use the number as the key and the string as the value.

While it will work in most cases, the order of properties in an object is not guaranteed. I would change this to either use an array of object or a map.

What if you wanted just the result form a single number? Or make a function that found the first number that gives fizzbuzz? Right now you are printing the result, so you can't do anything else with it. Make a separate function to get the result, which you can also use for other things.



function fizzBuzz(divisors = new Map([[3,'fizz'],[5,'buzz']]), maxNumber = 100) {
  for (var num = 1; num &lt;= maxNumber; num++) {
    console.log(fizzValue(divisors, num));
  }
}

function fizzValue(divisors, num) {
  var str = "";
  divisors.forEach((value, key) =&gt; {
   str += num % key == 0 ? value : '';
  });
  return (str ? str : num);
}

fizzBuzz();