FizzBuzz "unexpected token else


#1


It won't run, despite there being no visible problems. The error message says 'Unexpected token else'. In this spirit I examined the 'else' statement, but saw no immediate problem.


for (i=1; i=20; i++) {
    
    if (i % 3 === 0) {
        console.log("Fizz");
    }
      if else (i % 3 === 0) {
        console.log("Buzz");
    }
        if else  ((i % 5 === 0) && (i % 3 === 0)) {
        console.log("FizzBuzz");
    }
    else 
    { 
        console.log(i);
    }
};


#2

You have wrong if-else if-else syntax. should be:

if (condition1) {
    block of code to be executed if condition1 is true
} else if (condition2) {
    block of code to be executed if the condition1 is false and condition2 is true
} else {
    block of code to be executed if the condition1 is false and condition2 is false
}

#3

In my code, I wrote the "FizzBuzz" combination as a first condition, because the computer checks the conditons in order we write it. Otherwise, like in you example, the programme will execute number 15 as "Fizz" because it is true that it's divided by 3, and ignore the 3rd conditon. So for me this worked:
for (var i= 1; i <=20; i++) {
if((i % 3 === 0) && (i % 5 === 0)) {
console.log("FizzBuzz");
} else if (i % 5 === 0) {
console.log("Buzz");
} else if (i % 3 === 0) {
console.log("Fizz");
} else {
console.log(i);
}

        }

#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.