Javascript Ternary Operator Wants Extra Colon

This is my code:

var eatsPlants = false;

var eatsAnimals = true;

var category = eatsPlants ?  eatsAnimals ? "omnivore" : eatsPlants ? "herbivore" : eatsAnimals ? "carnivore" : "undefined";

I am getting an error that says that it needs another colon on the end and then an expression, but I have no other conditions.

1 Like

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

You have 4 ? and 3 : so you are definitely missing one.

I general, I strongly recommend against a quadruply nested ternary. The fact that yau are having trouble reading and debugging this nested ternary is exactly why.


The structure of your operator does seem a little off.

If you wanted to emulate this:

if (condition1 && condition2) {

It would look like this:

var result = condition1 && condition2 ? true : false

Which I think is what’s happening here.
I agree with what @JeremyLT says though, never a good idea to nest ternary’s deeply.

This is a good freeCodeCamp blog post on Ternary operators, you might find it useful to look at it.

Hope this helps!

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.