I am going through codeacademys JavaScript tutorials as i am new to it. The tutorial asks for the following:
Print out the numbers from 1 - 20.
The rules:
Hi please check the ¨=¨
for (i = 1; i <= 20; i++) {
if (i%3===0 && i%5===0) {
console.log("FizzBuzz");
}
else if (i%3===0) {
console.log("Fizz");
}
else if (i%5===0) {
console.log("Buzz");
}
else {
console.log(i);
}
}
When the value is divisible by 3 and not by 5, on the first If statement "Fizz" is printed.
Then on the second if statement, the last else is hit so the number will also be printed. You will need to change the if(i%5==0) to else if.
However there will be a problem now when (i%5==0 && i%3==0) as the else if for that will never be hit. You can fix this by putting this as the first comparison and changing the output to FizzBuzz.
Like this:
for ( i = 1; i <= 20; i++) {
if (i % 5 === 0 && i % 3 === 0) {
console.log("FizzBuzz");
} else if (i % 3 === 0) {
console.log("Fizz");
} else if (i % 5 === 0) {
console.log("Buzz");
} else {
console.log(i);
}
};
Make sure you understand why this fixes your issue before you move on as you will most likely make the same mistake again.
Add a comment if you would like me to explain clearer if you are struggling to work out why you have gone wrong.
Did you try it out yourself? Because when you run it you get this output:
1
2
"Fizz"
3
4
"Buzz"
"Fizz"
6
7
8
"Fizz"
9
"Buzz"
11
"Fizz"
12
13
14
"Fizz"
"Buzz"
16
17
"Fizz"
18
19
"Buzz"
As you can see, you are printing out the number even when you printed Fizz
and also you are actually supposed to print FizzBuzz
in a single line, instead of two separate ones.
To fix the former issue you should take a look at your if/else structure. You have a separate if at the beginning just for Fizz
. After that, you are handling the Buzz
separately as well and if there’s no match for it, it will print out the number. So although you already printed Fizz
you are still going to the last else
. So you should combine those two separate if blocks into a single one.
The other issue is that console.log
will always write a separate line. So in your case where you check for all the FizzBuzz
conditions, you should print FizzBuzz
. You will also want to check that first, otherwise the Buzz
condition will hit first without giving you a chance to print FizzBuzz
.
Try walking through the logic by hand. If i
is 1
, then only the last block works. If i
is 3
, the first block works. If i
is 5
, the second block works. And if i
is 15
, the second block works, and the third never gets a chance.
In general, have the most restrictive conditions run before the least restrictive. You should also notice and check carefully when two of your blocks are dissimilar. You have four blocks, and only one is an else
block.