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

Javascript Loops - Extra Credit answer

Hi guys,

Spent some time trying to figure out the answer to this, and came up with an answer. I wanted to know if this is correct (well, it seems to work, so I guess it's one answer), or if there was a much simpler way to do it.

Question:

Write a program that loops through the numbers 1 through 100. Each number should be printed to the console, using console.log(). However, if the number is a multiple of 3, don't print the number, instead print the word "fizz". If the number is a multiple of 5, print "buzz" instead of the number. If it is a multiple of 3 and a multiple of 5, print "fizzbuzz" instead of the number.

The code I have is:

var counter=1;

for (var counter=1;counter<101;counter=counter+1) {

if ((counter%3 && counter%5) && counter%3 && counter%5) {
    console.log(counter);
}
else {

    if (counter%3 || counter%5) {
            null;
        }
        else {
            console.log("fizzbuzz");
        }
    if (counter%3) {
        null;
    }
        else {
            console.log("fizz");
        }
    if (counter%5) {
        null;
    }
    else {
        console.log("buzz");
    }
    }
}

Apologies about the formatting, tried my best!

4 Answers

Try this

for (var counter=1;counter<=100;counter++) (counter % 3 == 0) ? console.log("fizz") : ((counter % 5 == 0) ? console.log("buzz") : console.log(counter));

I hope you find useful GJ

Thanks, that worked!

Dan Kinchen
Dan Kinchen
1,688 Points

This actually is not the answer. As it does not resolve this piece of the problem. "If it is a multiple of 3 and a multiple of 5, print "fizzbuzz" instead of the number."

Chris Harries
Chris Harries
3,067 Points

you may find it easier to use else if statements.

Example:

else if (counter % 3 == 0) {
    console.log("fizz")