SyntaxError: missing ( before condition


#1

My code is kicking back a syntax error...code is as follows..

for (var num = 1; num < 21; num++) {
    if (num / 3) {
        if (num / 5) {
            console.log ("FizzBuzz");
        }
        else {
            console.log ("Fizz");
        }
    }
    if else (num / 5) {
        if (num / 3) {
            console.log ("FizzBuzz");
        }
        else {
            console.log ("Buzz");
        }
    }
    else {
        console.log (num);
    }

SyntaxError: missing ( before condition

As far as I can tell all of my conditions are enclosed in brackets. I have scanned over the code multiple times to be sure; I was hoping someone could help me point out whats missing. It would be much appreciated.


#2

should be,

else if

Plus the for statement code block needs to be closed.

Since you are doing division, and i is never 0, the code will print 'FizzBuzz' repeatedly. Why is this? Because any non-zero number divided by three will be non-zero, so will evaluate to true in a conditional expression. Likewise, when dividing by 5, so that will also be true for all i !== 0.

We need to examine the remainder of the integer division which means using the remainder operator, %.

Following your logic, let's reconstruct the code:

for ( ... ) {
    if (num % 3 === 0) {
        if (num % 5 === 0) {
            console.log("FizzBuzz");
        } else {
            console.log("Fizz");
        }
    } else
    if (num % 5 === 0) {       // see note
        console.log("Buzz");
    } else {
        console.log(num);
    }
}

Note: The else if case will not need to test num % 3 since we already know it is not 0.


#3

Thanks! I just noticed the "else if" problem, right before this reply. I see what you mean about using a modulo vs division;
it makes sense now.