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

CODE REVIEW: Control Structures "extra credit"

The EC was to "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."

My solution:

var number = 1;

for (var counter=100; counter; counter = counter -1) {
  if (number % 3) {
    if (number % 5) {
      console.log(number);
      number = number + 1;
    } else {
      console.log("Buzz");
      number = number + 1;
    }
  } else {
    console.log("Fizz");
    number = number + 1;
  }
}

It got the job done but I keep thinking there must be a more elegant way to get the same or better results. All criticism welcome!

2 Answers

Umm ... There're couple of things I wanna say about the code.

  1. your code is incomplete, there's a case where If it is a multiple of 3 and a multiple of 5, print "fizzbuzz" instead of the number." it didn't handle.

  2. You initialize a counter variable, but you didn't make use of it anywhere in the for loop body, instead you declare another variable number outside of the for loop, and let it increment itself during the loop by number = number + 1;Now you have TWO variables to do the job where one would be suffice, and the bigger problem is that making the code more complicated that it needs to be.

If I write this solution in for loop, probably look something like this:

for (var num=1; num<=100; num++) {
    if (num%3===0) {
        if (num%5===0) {
            console.log("fizzbuzz");
        } else {
            console.log("fizz");
        }
    } else if (num%5===0) {
        console.log("buzz");
    } else {
        console.log(num);
    }
}

Thanks William,

This is my first attempt writing code. Your solution is much more elegant. I haven't learned to put an "=" inside the () in an if statement which made the logic harder to nail. I also haven't learned the "else if" statement. Thanks for posting your solution. I have a lot more to learn.