Problem with exercise: Use Multiple Conditional (Ternary) Operators

Tell us what’s happening:

Hi

What’s wrong with my code??

Regards,

Your code so far


function checkSign(num) {
  return (num>0)? "Positive": (num<0) ? "Negative" :(num==0) ? "zero";
}

checkSign(10);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:52.0) Gecko/20100101 Firefox/52.0.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/use-multiple-conditional-ternary-operators/

Hi,

Looks like there is a couple things going. In the ternary the last thing (“zero”) doesn’t need the (num==0) ? stuff because its basically the “else” portion of the statement. Also pos/neg shouldn’t be capitalized. A working snippet looks like:

return (num>0) ? "positive" : (num<0) ? "negative" : "zero";

Hope that helps!

3 Likes

Your code has been blurred out to avoid spoiling a full working solution for other campers who may not yet want to see a complete solution. In the future, if you post a full passing solution to a challenge and have questions about it, please surround it with [spoiler] and [/spoiler] tags on the line above and below your solution code.

Thank you.

2 Likes

A couple things:

  • Capitalization matters. Your returned strings must match those expected by the tests.
  • Your last ternary ((num==0) ? "zero") has a syntax error. It is missing the second half.

Ah tanks a lot! it worked! The last else portion of the statement doesn’t need a condition…I thought that by stating the condition it would be more clear, but apparently the syntax is not good the way I did it. Therefore I have to deduct that the last statement is always an “else” statement in the ternary test.

But I wonder: is a 4th, 5h (or even more) stacked conditional test possible?

Sometimes there are more than 2 “else if” and always an “else” condition on top of that.

Regardsn

Sure. It’s possible. Please don’t do it though. Ternaries don’t make your code functionally better - they should just be used when they make your code easier to read. That’s not very often, and certainly not the case when you are replacing a sequence of nested statement.