Else... if -- I think I learned it wrong

Hi, I am having some trouble with the rock, paper, scissors assignment. I went back to review the code I wrote in the conditionals section and I think I made an error here in the final else statement. Since, in this code, the script does not continue to run to the else statement, I did not notice it before. This will not log anything without the console.log(‘message’) portion, am I correct?

Following this, I am trying to write an if… else statement for the assignment as so:

I believe this is correct but I cannot check since the assignment hints show me an alternative ternary method of writing out the code. I would like to first make sure that I am correctly able to write out the long-form version of this conditional before using the ternary suggestion.

Can anyone see what my errors are here? I would really appreciate the explanation!

While your first code snippet will run (with parentheses following the else block), it is bad practise. The proper syntax for if…else if…else is as follows:

if (condition) {
//code
} else if (condition2){
//code 
} else {
//code
}

As well as this, you shouldn’t put semicolons after if blocks or for/while blocks (like you’ve done in your second screenshot). Putting them after arrow function declarations is encouraged, however.

What does this mean?

This means, you shouldn’t do this:

if (condition){
//code
};

But you should do this:

const someFunc = () => {
//code
};

See here for more on semicolons in JavaScript.

2 Likes

In the first example your error was putting the code to be executed in parenthesis rather than braces. (I guess ‘Just keep dreaming’ is the code supposed to be executed, even though you’re not doing anything with it like printing to the console or returning it?) The code in the parenthesis is always the condition that evaluates to truthy or falsy.
an else statement never has a condition as it is the default fallback. But it always has a code block in braces {}.
In your second example, your else statement is in the scope of the else if statement. They always have to be in the same scope:

if(condition){
// code to be executed
}
else if(condition){ // optional
// code to be executed
}
else{ // optional
// code to be executed
}
2 Likes

Thank you for the corrections, I appreciate it.

1 Like