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

Intro to Programming If/else Loops

I'm trying to do the extra credit problem on Intro to Programming in the Control Structures section.

The Extra Credit is called Fizz Buzz

Fizz Buzz

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.

Hint. Use loops and if/else statments. In javascript the % is the modulo, or remainder operator. a % b evaluates to the remainder of a divided by b. 11 % 3 is equal to 2.

So far I have this:

for (var number = 0; number <= 100; number = number + 1) {

console.log(number)

if (number % 5 == 0) }

    console.log("buzz")

}

if (number % 3 == 0) {

    console.log("fizz")

}

}

The problem is that this doesn't replace the numbers with "fizz" and "buzz." It prints "fizz" and "buzz" after the multiples of 3 and 5. Another problem I have is that I can't get it to print "fizzbuzz" when a number is both a multiple of 3 and 5. Any help would be appreciated.

18 Answers

Randy Hoyt
STAFF
Randy Hoyt
Treehouse Guest Teacher

I think the simpler logic is what was intended. You check the conditions in the reverse order that they are given in the instructions so that you can use the "else" at the end to print the number only if it's not divisible by 3 and not divisible by 5.

if ( 0 == i%3 && 0 == i%5) {
    console.log('fizzbuzz');
} else if(0 == i%3) {
    console.log('fizz');
} else if(0 == i%5) {
    console.log('buzz');
} else {
    console.log(i);
}

Does that help?

Since it's late on a Tuesday night, I'll throw in one other note for fun. If a number is divisible by 3 and by 5, then it is divisible by 15. :~) I might have written it like this; it's a little harder to read, but it should be a tiny bit faster since it only has to check one conditional instead of two:

if ( 0 == i%15 ) {
    console.log('fizzbuzz');
} else if(0 == i%3) {
    console.log('fizz');
} else if(0 == i%5) {
    console.log('buzz');
} else {
    console.log(i);
}

Randy,

I thank you for your support with this topic. After much trial and error I was able to come to nearly the same sequence that you have posted:

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

I look forward to more experimenting and fine tuning.

Thanks!

Hi Matias,

you have a logical error.

You need to first tell the programme that if both variables are multiples it should do fizzbuzz, then if that is not satisfied tell it to do sth if it is only a multiple of either and if none of that is the case print the number:

/* Extra Credit */
//loop through the numbers 1 to 100
var number;

for (number =1; number <= 100; number++) {

    //print the number, unless it is a multiple of five and three (fizzbuzz), three (fizz) or five (buzz)
    if (number % 3 ==0 & number % 5 ==0) {
        console.log('fizzbuzz');
    } else if (number % 3 == 0) {
        console.log('fizz');
    } else if (number % 5 == 0) {
        console.log('buzz')
    } else {
        console.log(number);
    }

}
// Starting Condition
var i       = 1,    // Start from 1, increase to 100
    printed = false,// record if we've printed i yet, per loop
    line    = '';   // what to log to the console

// Test Condition (one to a hundred)
while ( i <= 100 ) {

    console.info(' I am checking i='+i );

    line = '';

    if( 0 == i%3 ) {
        // Multiple of 3, print 'fizz'
        line += 'fizz';
        printed = true;
    }
    if( 0 == i%5 ) {
        // Multiple of 5, print 'buzz'
        line += 'buzz';
        printed = true;
    }

    if(!printed) {
        // Not printable yet, so print " i "
        line += i;
    }

    console.log( line );

    // Reset printed for next loop
    printed = false;

    // Increment i for the next loop around
    i++;
}

Try running it in the console?

Thanks for your response Andrew. I'm trying to make sense of that, but based on the videos I've seen, I don't know how they could possibly expect me to come up with the code that you wrote.

Hi Martin, (I may have an extra loop in mine - not checked this late in the night)

The code you wrote was almost there already.

The difference with my code and your code was that I wrote some comments on each line and did one thing differently to output the value.

I created a variable to hold the value I wanted to output, and then I modified that value depending on what condition was met.

In your code, you start your for loop correctly, but you console.log() the number too soon.

In this kind of problem, you need to look at the conditions that modify the output. Here, we have 2 conditions that modify the output, so we need to check those conditions first. If you moved your console.log() line from right after your for loop to after your %3 and %5 checks, then you can determine whether to print the number based on if whether or not fizz or buzz (or both) have been printed already.

In my code, I've checked the condition for fizz and set a variable to say whether or not i should print the " i " value later. I then check buzz, because I know that could still occur if 'fizz' has happened.

However, I don't want to print the number if fizz or buzz has happened, so I need to use that variable I was modifying to prevent printing the " i " value if either fizz or buzz has been printed.

When I reach that course, I might be able to modify this answer to be more helpful!

Thanks Martin

~also~

A simpler logic to read might be:

If ( 0 == i%3 && 0 == i%5) {
    console.log('fizzbuzz');
} else if(0 == i%3) {
    console.log('fizz');
} else if(0 == i%5) {
    console.log('buzz');
}

Out of idle curiosity, if you use this in Firefox's Firebug, why does '100' print after the loop?

var i=1,f='fizz',b='buzz';
while(i<=100){
    console.log( 0==i%15 ? f+b : (0==i%3 ? f : (0==i%5 ? b : i)));
    i++;
}

Thanks Andrew & Randy. That's what I was looking for. I tried something quite similar to that, but it wasn't working, so I abandoned it, but it's working now, and I understand it, so i can sleep peacefully.

Randy Hoyt
STAFF
Randy Hoyt
Treehouse Guest Teacher

Hey @Andrew,

Great question. There's a lot of good information about JavaScript in that answer. This might be more than you want to know about how JavaScript works for a Tuesday night, but here it goes. :~)

When you assign a value to a variable in the console, the value of that variable gets displayed in the console because it's the return value of the assignment. Just try this:

var i;
i = 100;

It will display 100.

If you execute multiple commands in one go, it will display the return value of the last command only. Try this:

var i;
i = 100;
var x;
x = 1;

It will display 1.

Interestingly enough, declaring a variable doesn't have a return value. Try this:

var i = 100;

This displays undefined.

If you followed all of that, you might be thinking that the console should display 101 at the end of the fizzbuzz example instead of 100. (At the end of this block of code, i has a value of 101.) Try this:

var i=1,f='fizz',b='buzz';
while(i<=100){
    console.log( 0==i%15 ? f+b : (0==i%3 ? f : (0==i%5 ? b : i)));
    i++;
}
console.log(i);

The console.log displays 101, and then it displays undefined because console.log does not return a value.

The reason that i++ returns 100 instead of 101 is because of how the ++ operator works. If you put it after the variable, ++ increases the i variable but returns the original value. Try writing this instead:

var i=1,f='fizz',b='buzz';
while(i<=100){
    console.log( 0==i%15 ? f+b : (0==i%3 ? f : (0==i%5 ? b : i)));
    ++i;
}

With the ++ in front of the i, it increases the i variables and returns the new value.

I suspect Jim wanted you to write the loop a little bit differently so that i actually does have a value of 100 at the end.

var i=0,f='fizz',b='buzz';
while(i<100){
    i=i+1;
    console.log( 0==i%15 ? f+b : (0==i%3 ? f : (0==i%5 ? b : i)));
}

This way, it displays all the values correctly and then ends with an "undefined" ... which is the return value of the final console.log call.

Does all that make sense?

Hi Randy.

In between replying to Martin and your answer, I've just completed the task that this relates to and completed the second console Lesson.

Your answer made a great deal of sense! I love the extra detail and clarity of it.

It would be great to attach comments and replies to the linked courses for others to pick up extra knowledge along the way.

Thanks for a thorough response!

This was a fun exercise. I'm no math wizard, so I usually take the brute force "it works" approach, then come back later to optimize or look for new patterns.

<script type='text/javascript'>
    for(var i=1; i <= 100; i++)
    {
        var multOfThree = i % 3;
        var multOfFive = i % 5;

        if( (multOfThree + multOfFive) === 0)
            console.log('FizzBuzz!' + '(' + i + ')');
        else if(multOfThree === 0)
            console.log('Fizz!' + '(' + i + ')');
        else if(multOfFive === 0)
            console.log('Buzz!' + '(' + i + ')');
        else
            console.log(i);
    }
</script>
Randy Hoyt
STAFF
Randy Hoyt
Treehouse Guest Teacher

Hey @Sam,

Now you got me thinking about the best way to optimize this code. :~) Very fun! Your approach and my approach are different in interesting ways.

  • Your code performs two divisions and one addition every single time.
  • My code performs only one division in some cases, but two in others and three in still others.

I guess we could compare the total number of math functions performed when looking at the first 15 numbers. (We have the same number of conditional checks I think.)

  • Your code performs 45 total math functions (15 additions and 30 divisions) when looping through 15 numbers.
  • My code performs the following 1 division only one time (15), 2 divisions 4 times (3, 6, 9, 12), and 3 divisions the other 10 times (1,2,4,5,7,8,10,11,13,14). That means I end up with 39 total math functions (all divisions).

After that, I guess the questions are these: Is division slower than addition? (If so, how much slower?) Is dividing by 15 (which I do 15 times but you never do) slower than dividing by 3 or 5 (which is all you do)? I'm afraid these questions are too close to the metal for me to answer!

I know absolutely nothing about performance testing or tuning quite honestly :blush: I tried using jsperf just for fun though.

Here's the showdown!

My control case of the platform using an identical code snippet however has a bit of deviation, which I'm sure stems from multiple reasons (system processes, browser engine, memory management, etc.) So, yeah, results are inconclusive!

Randy Hoyt
STAFF
Randy Hoyt
Treehouse Guest Teacher

Very cool, @Sam. :~)

I also really like @Andrew's approach. It's probably more complicated than Jim had in mind (based on what badge it is attached to), but that's one of the ways I might have really coded it.

I would make my final decision about how to code it in real life based on what would be easiest for another developer to figure out if they had to read the code. I think the easiest code to read would be Sam's, with one modification:

Instead of this ...

if( (multOfThree + multOfFive) === 0)

... I'd probably prefer this ...

if( (multOfThree === 0) && (multOfFive === 0)) {

This code is checking if the number is divisible by three and if it is divisible by 5. My approach (i%15) and @Sam's approach (i%3 + i%5) to check this are probably both a little too complicated to understand at first glance. Using an actual AND conditional might be a little simpler.

You bring up a good point about readability, which I imagine grows more and more important when your code starts to swell. Really cool to see all the different approaches!

Hi guys. Really late here but, I just was working on this. Based on the lesson, this is the answer I got.

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

Will this give you fizzbuzz if your counter % 3==0 and counter % 5 == 0 ?

Guess my answer the the problems not as efficient but here's what i came up with after a while:

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

What am I doing wrong?

```for (var i=1; i <= 100; i++) {

 if(i%3 == 0) (
     console.log("fizz")
 )   

 else(i%5 == 0) (
     console.log("buzz")
 )

else if(i%3 == 0 && i%5 == 0) (
      console.log("fizzbuzz")
)

console.log(i);

};```

I added an answer below. the order of the statements should be if, else if, else. in a sense like if something is the case than do this, otherwise check whether something else is the case, if all fails do the last statement

<pre>for (i = 1;i<=100; i++){ if (i % 3 == 0 && i % 5) { console.log("fizzbuzz"); } else if (i % 3 == 0 ) { console.log("fizz"); } else if (i % 5 == 0) { console.log("buzz"); } else { console.log(i); } }</pre>