I need a deeper understanding of the placement of parenthesis. I followed the format correctly and I have the correct answer but I still am not 100 percent on why they go in certain places


#1



var computerChoice = Math.random();
if (computerChoice < 0.34) {
	computerChoice = "rock";
} else if(computerChoice <= 0.67) {
	computerChoice = "paper";
} else {
	computerChoice = "scissors";
};

var compare = function(choice1, choice2)
{
if(choice1 === choice2){
return "The result is a tie!";
     } 
else if(choice1 === "rock"){
if(choice2 === "scissors"){
return "rock wins";
}else{
return "paper wins";
       }
    } 
else if(choice1 === "scissors"){
if(choice2 === "paper"){
return "scissors wins";
}else{
return "rock wins";
       }
    } 
else if(choice1 === "paper"){
if(choice2 === "rock"){
return "paper wins";
}else{
return "scissors wins";
       }
    }
};
compare(userChoice,computerChoice);



Replace this line with your code. 



#2

also please explain the double parenthesis and triple parenthesis in particular


#3

you create a function: (simplified example)

compare(){

}

inside your compare the first thing you do is to determine if the result is a tie:

compare(){
 if (equal){

  }
}

see? now we already have a double closing curly bracket (one for if, one for the function)

then we have the same code 3 times. lets do one of them. lets say i check if choice1 is rock:

compare(){
 if (equal){

  }
  else if(choice1 == "rock"){

  }
}

now, inside your if statement there are two options, the computer choose scissors, in which case the user wins, or the computer choice paper, in which case the computer one, to determine this we nest a if and else inside the else if:

else if(choice1 == "rock"){
  if(choice2 == "scissors"){
    // user wins
  } else {
    // computer wins, since choice2 has to be paper
  }
}

and you repeat this for your choice1 is scissors and your choice is papers.

All the curly brackets will come, because of the nested if statements, and at the very end an additional one to close your function


#4

Parentheses are part of the syntax, they're required to create various patterns that the interpreter knows how to parse. For example, a function call is an expression followed by () with optional arguments between the parentheses. An if-statement goes like if (expression) statement [else statement] where the else part is optional (that's what I mean with the square brackets). As you see, parentheses are part of that specification so they simply have to be there or what you wrote isn't matching that pattern and thus isn't an if-statement.

Bottom line, look up examples for what you're trying to do.


#5

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