Skip to content

Instantly share code, notes, and snippets.

@tomhodgins
Last active August 29, 2015 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomhodgins/0feaab1de37b8f5a3ae7 to your computer and use it in GitHub Desktop.
Save tomhodgins/0feaab1de37b8f5a3ae7 to your computer and use it in GitHub Desktop.
FizzBuzz in JavaScript
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>FizzBuzz in JavaScript</title>
</head>
<body>
<script>
function fizzBuzz() { // Let's create a function called FizzBuzz
var message = '', digit; // We'll start with an empty message, and a placeholder for the digits
for (var i=1; i<101; i++) { // Run this loop for 100 iterations, and use 'i' to represent the iteration count
if ((i%3 == 0) && (i%5 !== 0)) { digit = 'fizz'; } // If the iteration count is divisible by threee but not by five, let the digit in the message say 'fizz'
else if ((i%5 == 0) && (i%3 !== 0)) { digit = 'buzz'; } // If the iteration count is divisible by five but not by three, let the digit in the message say 'buzz'
else if ((i%3 == 0) && (i%5 == 0)) { digit = 'fizzbuzz'; } // If the iteration count is divisible by both three and five, let the digit in the message say 'fizzbuzz'
else { digit = i; } // Otherwise, if the iteraction count is neither divisible by three nor five, let the digit in the message say the iteration count
message = message+digit+' '; // The message is equal to the existing message plus the digit for this iteration count, followed by a space
}
return message; // Once 100 iterations are complete, return the result
}
document.write(fizzBuzz());
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment