How Are These Codes NOT Identical?


#1

Far as I can tell, except for the position of one statement, these codes are the same, but only one was accepted:

Anyone know what causes only one to work?

ERROR CODE:

for (var n = 1; n >= 1 && n <= 20; n++) {

if (n % 3 === 0) {
console.log("Fizz");
}
else if (n % 5 === 0) {
console.log("Buzz");
}
else if (n % 3 === 0 && n % 5 === 0) {
console.log("FizzBuzz");
}
else {
console.log(n);
}
};

OUTPUT:

1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
Fizz
16
17
Fizz
19
Buzz

Error: “You printed Fizz when you should have printed FizzBuzz”

ACCEPTED CODE:

for (var n = 1; n >= 1 && n <= 20; n++) {

if (n % 3 === 0 && n % 5 === 0) {
console.log("FizzBuzz");
}
else if (n % 3 === 0) {
console.log("Fizz");
}
else if (n % 5 === 0) {
console.log("Buzz");
}
else {
console.log(n);
}
};

OUTPUT:

1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
17
Fizz
19
Buzz


#2

What is this?

Seriously. Did someone miss the lesson on for statements?

Don't get me wrong, the expression is perfectly valid, but is it necessary?


#3

I had a feeling it probably wasn't perfectly accurate, but it did fit the requirement & did get the job done, the only issue was whether it was in one position or another, which clearly made a difference, but I don't understand why.


#4

My point, eactly. Don't leave this problem until you have an answer.


#5

I got this same error. I think it is because of the ordering of the if statements. The way it was written first, if the number was divisible by 3, it automatically printed Fizz and didn't bother to check if the number was also divisible by 5. By putting the && statement first, it proceeds to check the others IF the first one fails to be true. I'm not sure I'm saying this clearly, but that is how I interpreted the error.


#6

You did say it clearly, & I think you’re right. After reviewing, & remembering, a few basics, I guess I was expecting the computer to go back & redo something, when the code did not include such an instruction.


#7

Compound always before simple. That is the order that will go the correct branch.


#8

I think, without giving it away, pay attention to where your variable n begins when reviewing your code. (as far as what was pointed about about the for loop, not about the order of conditionals)


#9

Sorry, but not getting what this is referring to - instructions regarding the numbers were "count from 1 to 20" - so I don't know what "attention" should be necessary regarding where it begins - seems to be a given that it needed to begin at 1, and if at least one correct method of indicating that had not been used, I imagine the code would not have worked, (either that or there's an error in the Course-Checker, or you're referring to something else & I just can't figure exactly what).