Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript Introduction to Programming Control Structures Loops

FizzBuzz extracredit code working ?

Hey everyone, I was just wondering why this code doesn't work :

for (var counter = 100; counter; counter = counter -1) {
 if (counter % 5 == 0) {
   console.log("Buzz");
 }
 else if (counter % 3 == 0 && counter % 5 == 0) {
   console.log("FizzBuzz");
 }
 else if (counter % 3 == 0) {
   console.log("fizz");
 }
 else {
   console.log(counter);
 }
}

and this one does

for (var counter = 100; counter; counter = counter -1) {
 if (counter % 3 == 0 && counter % 5 == 0) {
   console.log("FizzBuzz");
 }
 else if (counter % 5 == 0) {
   console.log("Buzz");
 }
 else if (counter % 3 == 0) {
   console.log("fizz");
 }
 else {
   console.log(counter);
 }
}

Isn't it the same, if I put the && in the if or in the else if ?

1 Answer

The two part requirement has to come first because they will be evaluated in order. In the first example, if the counter is divisible by 5, the IF statement is being evaluated before the ELSE IF statement gets a chance and then the loop continues.

Hope that makes sense to you, let me know if you need it explained further.