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

Tell us what’s happening:

I’ve been working on this ternary operator for a while now. I first began with return hit > 0 ? score : default_score and that did not work then I checked the forum which got me to return hit > 0 ? hit : default_hit but that did not work either. I realized that the other help posts seemed to be for another step , placed under step 149 maybe because the course changed a little and the steps changed? And there might not be that many questions on this particularly, so I thought to ask

Your code so far

<!-- file: index.html -->

/* file: styles.css */

/* file: script.js */
// User Editable Region

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

// User Editable Region

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36

Challenge Information:

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

Hello,

You shouldn’t use default_hit there.

According to the direction, it said that when hit is greater than 0 it should return hit when true and return 0 if false.

keep it up! :smiley:

So you’re suggesting this…

return hit > 0 ?  0 <= 0 ;

almost…

so here how that shorthand if...else statement works:
condition ? executeWhenTrue : executeWhenFalse;

it’s almost right - you added the 0 when it’s false, but you made a mistake when you changed the hit when the condition is true. Also, you removed the colon : between the true and false.

I hope you understand :smiling_face:

It seems you’re implying this…

return hit > 0 ? hit <= 0

Okay adding a : works, but isn’t the notation supposed to be <=

no, it should be :

the shorthand if...else statement:

return hit > 0  ?  hit  :  0 ;

is just the same as this:

if (hit > 0) {
   return hit;
} else {
   return 0;
};

on the shorthand if...else, the colon : works like a divider to separate the first expression to second expression.

Edit: the shorthand if...else statement is called a ternary operator.

2 Likes