3...And the good! - Introduction to Objects I


#1

I managed to get the following code working when I use console.log to print "Fizz", "Buzz" and "FizzBuzz", but when I use return, I get the following error: SyntaxError: Illegal return statement. Can somebody explain to me why I can't use return statements/or how to use them correctly?

Here is my code with the return statements:

for (var i = 1; i < 21; i++) {
if (i % 3 === 0) {
if (i % 5 === 0) {
return "FizzBuzz"
}
else {
return "Fizz"
}
}
else if (i % 5 === 0) {
return "Buzz"
}
else {
console.log(i);
}
};

Thanks


#2

Your logic is fine. Change the return to console.log() in the top three branches.


#4

Cheers. Do you know why I can't use return statements instead?


#5

... why I can't use return ... ?

Number one, because there is no function, and return can only be called from inside a function. That notwithstanding, were this loop in a function, it would terminate not just the loop, but the function as well. Abruptly, I might add.

For the purposes of this program, logging each stage is the goal.


#6

Thanks so much for the clear explanation!