3/33 And The Good! - Duplicate number is FizzBuzz exercise


#1

Hi people,

I'd be grateful if someone could tell me why my code for the FizzBuzz task is creating duplicate numbers.

Here is my code:
for (var i = 1; i < 21; i++){
console.log(i);
if((i % 3 === 0) && (i % 5 === 0 )){
console.log("FizzBuzz");
}
else if (i % 5 === 0){
console.log("Buzz");
}
else if( i % 3 === 0){
console.log("Fizz");
}
else{
console.log(i);
}

}

And this is what is printed in the console:

1
1
2
2
3
Fizz
4
4
5
Buzz
6
Fizz
7
7
8
8
9
Fizz
10
Buzz
11
11
12
Fizz
13
13
14
14
15
FizzBuzz
16
16
17
17
18
Fizz
19
19
20
Buzz

Any ideas?

Kind regards,

Sam


#2

One unneeded extra console.log statement

for (var i = 1; i < 21; i++){
console.log(i); // <---------------------------- you have an extra console.log here
if((i % 3 === 0) && (i % 5 === 0 )){
console.log("FizzBuzz");
}
else if (i % 5 === 0){
console.log("Buzz");
}
else if( i % 3 === 0){
console.log("Fizz");
}
else{
console.log(i);
}
}

#3

Thanks for clearing that up cucumkid. Much appreciated!


#4

Is there a reason you have to check for the dual condition before checking the individual ones? On mine i had the first if statement last in the order and I couldn't get it to produce FizzBuzz.


#5

Yes FizzBuzz needs to be checked first because any number that would come up FizzBuzz, will also match Buzz and Fizz. E.g. 15 % 5 = 0 and 15 % 3 = 0 so it will answer one of those (which ever it hits first) and never reach the FizzBuzz check.


#6

Could you check my code, to me it seems right

for (var i = 0; i < 21; i++) {
if (i % 3 === 0) {
    console.log("Fizz");
    } else if (i % 5 === 0) {
        console.log("Buzz");
        } else if ((i % 3 === 0) && (i % 5 === 0)) {
            console.log("FizzBuzz");
            } else {
                console.log(i);
                }
}

#7

cucumkid thanks got it, it with the i


#8

you have to check the dual conditon first...so swap the first and the third conditon...