I want to print the strings: "Fizz", "Buzz" and "FizzBuzz" in console.log
instead of the number they refer to. The point is that until now I can get both number and string, but I don't know how to overcome the number value with the string. For example, the console.log
of the code below should be 1 2 Fizz
and not 1 2 3 Fizz
.
//Define listNumber
var listNumber;
//Generate numers from 1 to 100
for (i = 1; i <= 100; i++) {
listNumber = i;
console.log(listNumber);
if ((listNumber % 3 == 0) && (listNumber % 5 == 0)) {
console.log('FizzBuzz');
} else if (listNumber % 3 == 0) {
console.log('Fizz');
} else if (listNumber % 5 == 0) {
console.log('Buzz');
}
}
You log the initial value before you do your check. Simply move it to the end of the evaluation, so that if it's neither Fizz
, Buzz
or FizzBuzz
it prints the actual number.
//Define listNumber
var listNumber;
//Generate numers from 1 to 100
for (i = 1; i <= 100; i++) {
listNumber = i;
if ((listNumber % 3 == 0) && (listNumber % 5 == 0)) {
console.log('FizzBuzz');
} else if (listNumber % 3 == 0) {
console.log('Fizz');
} else if (listNumber % 5 == 0) {
console.log('Buzz');
} else {
console.log(listNumber);
}
}