Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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.