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

What is wrong with my code?

I am trying to set the result to "fizzbuzz" but I only get "fizz". Anyone know what the problem may be? Thanks.

var x= 15;
var result;
 if (x % 3 === 0) {
    result = "fizz";
} else if (x % 5 === 0) {
    result = "buzz";
} else if (x % 3 === 0 && x % 5  === 0) {
    result = "fizzbuzz";
} else  {
    result = "x";
}

1 Answer

Jason,

One thing to remember is that once a condition is met the evaluation ends. So in this case 15 % 3 === 0 is true so it sounds there. You might consider just changing the order of the checks you do.

var x= 15;
var result;
if (x % 3 === 0 && x % 5  === 0) {
    result = "fizzbuzz";
} else if (x % 3 === 0) {
    result = "fizz";
} else if (x % 5 === 0) {
    result = "buzz";
} else  {
    result = "x";
}

Back in 2007 I blogged about doing FizzBuzz using Ruby. Even if you're not familiar with Ruby this might help give you some ideas in Javascript: http://innovativethought.net/2007/04/21/cleaning-up-my-ruby-fizzbuzz/.

You could just concat a string together or join an array like I do in my blogged example. Something like:

var x = 15;
var result = "";
if (x % 3 === 0) { result += "fizz" }
if (x % 5 === 0) { result += "buzz" }