FizzBuzz Code Golf in JavaScript
The FizzBuzz problem is defined as:
For the numbers 1 to 100, print "fizzbuzz" if the number is divisible by 3 and 5, "fizz" if it's only divisible by 3, "buzz" if it's only divisible by 5, and nothing if it's divisible by neither 3 nor 5. Each printed word should be on it's own line.
I'm going to attempt to code golf this in javascript, working my way down from an initial, verbose attempt. Here's the function at 225 characters:
Down to one line, 182 characters:
Spaces removed, 144 characters:
Brackets and semicolons removed, 137 characters:
Removed variable declaration, renamed console, <=100
turned into <101
, 123 characters:
Removed console rename, stored string to print, print at end, check that string has value before printing (using javascript's ||
as a coalesce), 122 characters:
Changed logic to concatenate strings instead of building all three options, 83 characters:
I think that's as low as I can get it. If you know anything I can do to shorten it, let me know!
Update 11/12/13:
I thought of another tweak I could make. Use the ternary operator to set or concatenate the value of r
instead of if
statements. Updated result, 71 characters: