Use Multiple Conditional (Ternary) Operators HELP ME

Tell us what’s happening:

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.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36.

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

"negative":(num===0)?"zero"

Do you see something missing in the second part?

can you help me to point out this mistake . I can not find out what i missed

a ternary operator is made like this: (check this) ? (if true execute this) : (if false execute this)

the part to execute can be an other ternary operator, but it still need to have all the three parts

the last part where you have (num === 0) ? "zero" doesn’t fit the pattern

Why is FCC teaching this??? This is horrible practice and should never be used.

If you’re trying to spot your mistake then it can be easier to read if you follow a pattern:

function checkSign(num) {
  return num > 0
     ? "positive"
     : num < 0
        ? "negative"
        : num === 0
          ? "zero";
          : // this is missing...
}

Pattern:

return IF_CONDITION
   ? RUN_THIS_IF_TRUE
   : RUN_THIS_IF_FALSE;

To make it work correctly, replace it to

function checkSign(num) {
  return (num>0)?"positive":(num<0)?"negative":"zero";
}
1 Like

The nested ternary pattern is plenty readable when you lay it out like a truth table. I simplified the logic from your function a little, but it’s the formatting that’s important here.

function checkSign(num) {
  return num > 0 ? "positive"
       : num < 0 ? "negative"
       : "zero";
}

BTW, never nest ternaries in PHP, since they got the associativity completely wrong.

1 Like

It’s still doable in PHP (by using parenthesis)., but you should never do it in any language.

I teach JS to entry & junior level programmers at the FCC Meetup groups,. and by far they prefer the method I listed.

I guess that’s a good reason. I just wish there was an emphasis not to use it.

I personally never override the no-nested-ternary rule in eslint, which is on by default.

1 Like