Riza Riza - 6 months ago 20
HTML Question

Fizzbuzz Code Not Working

I need some help. My fizz-buzz code is correct but when my page loads it is not showing.
Can someone help what I am missing?

Here is my html:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>FizzBuzz Challenge</title>

</head>
<body>
<h1>FizzBuzz Challenge</h1>
<p>View FizzBuzz Output</p>
<script type="text/javascript" src="js/FizzBuzz.js"></script

</body>
</html>


Here is my JavaScript code:

function FizzBuzz() {
var display = numCount;

if (numCount % 3 == 0) {
display = ("Fizz");
} else if (numCount % 5 == 0) {
display = ("Buzz");
} else if (numCount % 3 == 0 && numCount % 5 == 0) {
display = ("FizzBuzz");

} else {

console.log(display);
}
}

for (numCount = 1; numCount < 100; numCount++) {
FizzBuzz(numCount);
}

Answer

I would recommend this JavaScript code :

(function executeThis() {

    function FizzBuzz(numCount) {
        if (numCount % 15 == 0) {
            document.write("FizzBuzz ");
        } else if (numCount % 3 == 0) {
            document.write("Fizz ");
        } else if (numCount % 5 == 0) {
            document.write("Buzz ");
        } else {
            document.write(numCount + ' ');
        }
    }

    for (var numCount = 1; numCount < 100; numCount++) {
        FizzBuzz(numCount);
    }
}());

Note that :

  1. If a number is divisible with both 3 and 5 it is divisible with 15
  2. document.write displays things in the page. You may also want to have a look at Angular or jQuery or another such library/framework.
  3. add a space or other delimiter after each string you print
  4. try to keep your variables like numCount local in each function instead of making them global
Comments