Basic JavaScript - Use Multiple Conditional (Ternary) Operators

Basic JavaScript - Use Multiple Conditional (Ternary) Operators
0.0 0

#1

I wrote this code and it will not work but i am convinced this is correct? Can someone please enlighten me?

return (num > 0) ? “positive” : (num < 0) ? “negative” : (num === 0) ? “zero”;

Thanks in advance,
Hassan


#2

What error message do you get?


#3

Hi, when i click on “Run all tests” nothing happens … the only error i notice is the last “}” has a red underline…


#4

I think the best way to approach this problem is to follow the format of the example given on the left hand side of the screen.

My understanding of it (and please someone feel free to call me out on this because I’m not 100% sure) is that in your format you are essentially saying:

IF (num > 0) { return “positive”};
ELSE IF (num < 0) { return “negative”};
ELSE IF (num ===0) { return “zero”};

and with conditional operators this will not work because you don’t have a final ELSE statement. You therefore need to find a way to turn your last IF/ELSE statement into just an ELSE


#5

it worked thank you so much! I changed the code to what you said…

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

This is my first time posting here and with community responding it made me understand my problems better.

Thanks zdflower and hogues.uk ^_^.


#6

I think it could work this way:

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

And you need both the result for the true branch and for the false branch. That’s why the “not possible”.


#7

You are not returning completely. This is one situation where a code formatter would help you debug this.

I think you can debug this yourself. Go to https://prettier.io/playground/ and type in your statement word by word. Don’t paste it in because it’ll blow the error trace. Do that and it’ll give you a hint on what’s going on.


#8

Wow this is awesome thanks for telling me about the website. I am going to paste so much code into here :slight_smile: so far it did not like " but preferred single like this ’ haha …


#9

I should have mentioned this –

This site is for formatting code correctly, with minor options. Quotes and semi-colons can be toggled on the bottom left button, show options. These options are personal and don’t affect how code runs.

Also, if you use an editor like VScode, you can install this plugin.