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 trialJonny Allen
3,362 PointsJavascript 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
Gustavo Jose Morales Carpio
34,077 PointsTry 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
Jonny Allen
3,362 PointsThanks, that worked!
Dan Kinchen
1,688 PointsThis 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
3,067 Pointsyou may find it easier to use else if statements.
Example:
else if (counter % 3 == 0) {
console.log("fizz")