Dont know whats going wrong


#1


I always get the following error, SyntaxError: Unexpected token {
What does it exactly mean? If i remove the last to curly braces after the last computerChoice my code kind of works, but gives me an error like: ReferenceError: computerchoice is not defined
I KNOW, but if i define it i get an error too.. ??

Please help me out here..


var userChoice = prompt("Do You choose rock, paper or scissors?")

var computerChoice = Math.random();
    console.log(computerChoice);
  
    if (computerchoice <= 0.33) {
        computerChoice="rock";
    } else if (computerChoice = 0.34 && computerChoice <= 0.67) {
        computerChoice="paper";
    } else (computerChoice = 0.67 && computerChoice <= 1) {
        computerChoice="scissors"; }


#2

You assign values with an = sign. You might want to use a > sign here for proper syntax within your else if condition.

An else statement never takes a condition since it only runs if prior if statement conditions aren't met.


#3

this bit:

else if (computerChoice = 0.34

you should check if .34 is equal or greater then >=

Actually, you can just leave this out, if the number would have been smaller then .34 the if clause will run.

Also, else can't have a condition since it is everything else


#4

But if i leave everything untouched and just remove the last 2 curly brackets, the code just works only gives the error that the condition is not defined. I just don't get it..


#5

It's confusing. There's a pretty good discussion on it here:

What I got from it is that you don't need curly braces for an if/else if/else statement when the condition executes a single line of code. Problems arise when you leave out braces on multiple lines of code and multiple if/else if/else statements.


#6

It's interesting.

This concept also applies to many other languages including java and c#. But as the guy in that thread mentions - it's usually best to just include it anyway to make the code more readable and maintainable.


#7

@rubyace40397, but the problem is with the conditions themselves, not the brackets.

agnusbeef and biff75, please stay on topic, otherwise create a new (private) topic. Thank you


#8

I would argue that it is on topic because OP was still curious as to why his code was still working even without the curly braces. Nonetheless I respect your request.


#9

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