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

Emmanuel Prempeh
Emmanuel Prempeh
1,769 Points

My Codes for the Extra Credit Assignment

This is what I did for the extra credit. Is anyone with alternative approach? Cheers!

for (var i = 1; i <= 100; i++) {
    //console.log(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)
    }
};

6 Answers

Diego Villaseñor
Diego Villaseñor
12,615 Points

This is mine, though it is not as elegant:

var counter = 0;
while (counter<100){
  counter=counter+1;

  if (counter%3) {
   if (counter%5) {
     console.log(counter);
   } else {
     console.log("Buzz");
   }
  } else {
    if (counter%5) {
      console.log("Fizz");
    } else {
      console.log("Fizzbuzz");
    }
  } 
}

That looks pretty good. I did not do this particular task yet but I am guessing you are trying to find numbers divisible by 3 and 5 between 1 and 100 and print something to the screen if you find the number? If that is the case I guess you can also create a separate function? This should definitely be the primary way of going about it though.

Mohammed Khalil Ait Brahim
Mohammed Khalil Ait Brahim
9,539 Points

If I may I thunk there is a small mistake there Let's say take 15 which is both divisible by 5 and 3 then Your if statements would output only "Fizz" Because (15 % 3 == 0) is true no ? And if you run this code I am sure no "fizzbuzz" would be printed to the screen. So the order of the if statement should change

   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)
    }
Emmanuel Prempeh
Emmanuel Prempeh
1,769 Points

Thank you for the correction!

Here is my code

for (var num = 100; num; num = num - 1) {
    if (num % 15 == 0) {
        console.log("fizzbuzz");
    }

    else if (num % 3 == 0) {
        console.log("fizz");
    }

    else if(num % 5 == 0) {
        console.log("buzz");
    }

    else {
        console.log(num);
    }

}