Learn Basic JavaScript by Building a Role Playing Game - Step 146

Tell us what’s happening: I can get to pass this ternary operator :

Step 146

If you play the game in its current state you might notice a bug. If your xp is high enough, the getMonsterAttackValue function will return a negative number, which will actually add to your total health when fighting a monster! You can fix this issue by using a ternary operatorto ensure negative values are not returned.

The ternary operator is a conditional operator and can be used as a one-line if-else statement. The syntax is: condition ? expressionIfTrue : expressionIfFalse.

Here is an example of returning a value using an if-else statement and a refactored example using a ternary operator:

if (num > 5) {
  return 'num is greater than 5';
} else {
  return 'num is smaller than or equal to 5';

return num > 5 ? 'num is greater than 5' : 'num is smaller than or equal to 5';

In getMonsterAttackValue, change return hit to a ternary operator that returns hit if hit is greater than 0, or returns 0 if it is not.


The challenge seed code and/or your solution exceeded the maximum length we can port over from the challenge.

You will need to take an additional step here so the code you wrote presents in an easy to read format.

Please copy/paste all the editor code showing in the challenge from where you just linked.

function getMonsterAttackValue(level) {
  const hit = (level * 5) - (Math.floor(Math.random() * xp));
  return hit > 0 ? 'hit' : '0';

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.5 Safari/605.1.15

Challenge Information:

Learn Basic JavaScript by Building a Role Playing Game - Step 146

Please post your code for us so we can help you

When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (').

What error message are you getting? Looking carefully at the exact wording of the error message can often help.


You should use a ternary to return hit if hit is greater than 0

I have noticed in a lot of these steps that you must return exactly what they say - and often if they want a string they will say so

1 Like