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.
WARNING
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));
console.log(hit);
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