Question related to the topic onTask 146

Hi! I was in task 146 of the Role Playing Game and there is an explanation on how to transform a if-else statement into a ternary operator

// if-else statement
if (score > 0) {
  return score
} else {
  return default_score
}

// ternary operator
score > 0 ? score : default_score

My question is this: To be exactly true the code above, shouldnt it be this?

// if-else statement
if (score > 0) {
  return score
} else {
  return default_score
}

// ternary operator
score > 0 ? return score : return default_score

That made me a bit confused on the answer of the task, because they asked to return hit if hit was higher than 0 so I did

"hit > 0 ? hit : 0;"

based on the example shown first, but the right answer was

return hit > 0 ? hit : 0;

Besides the first question I made up there, is it also correct to make this?

hit > 0 ? return hit : return 0;

The explanation is missing something. You don’t call return on each part of the ternary. That’s kind of the point. The first is actually correct.

It just needs one more word to make it actually properly correct.

// if-else statement
if (score > 0) {
  return score
} else {
  return default_score
}

// ternary operator
return score > 0 ? score : default_score

More on ternaries here.

Happy learning. :slight_smile:

1 Like

Hello!
to elaborate on what a2937 said:

What you are seeing here is the difference of how functions and how ternaries are working. A traditional if else statement is a function and needs a return statement, or it won’t do anything.
In a ternary the JavaScript engine automatically returns the result under the hood on runtime. A ternary can only be a boolean that is either truthy or falsy. The engine has a library of falsy values like ‘null’, NaN, aso… Everything that isn’t in the false library can be returned as true by the engine, without you needing to instruct it to do so.

1 Like

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