FAQ: Advanced JSX - JSX Conditionals: The Ternary Operator

This community-built FAQ covers the “JSX Conditionals: The Ternary Operator” exercise from the lesson “Advanced JSX”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Web Development

Learn ReactJS: Part I

FAQs on the exercise JSX Conditionals: The Ternary Operator

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head here.

Looking for motivation to keep learning? Join our wider discussions.

Learn more about how to use this guide.

Found a bug? Report it!

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

I thought you couldn’t use conditionals in JSX statements? Isn’t the ternary operator a JS conditional?

1 Like

Why in the exercise you have to enclose the ternary operator between brackets? Its not that its an array, right? An even more in the previous exercise the img is found by using “pics.kitty”, however with the ternary operator the final result would be “pics[kitty]”. Can someone please explain this?

5 Likes

Same question. Why brackets?

Hello dude. i have a question in the Ternary Operator.

const img = <img src={pics[coinToss() === ‘heads’ ? ‘kitty’ : ‘doggy’]} />;

in example above, why cointToss() must be wrapper by side brackets ?

It’s not coinToss but the entire expression, as it will result in keyword. It’s that keyword that will end up in the square brackets to lead us to pics[keyword].

1 Like

Regarding the use of [ ] in this exercise, it’s easier to understand the use of the ternary like this:

const img = <img src={coinToss() === 'heads' ? pics.kitty : pics.doggy} />;

The [ ] is just addressing the pics object differently, by having it resolve to either pics['kitty'] or pics['doggy']

11 Likes

Reporting buggy exercise:

Getting an error when my response is actually correct. Attached error image below, versus what the solution shows.

Only allows me to attach 1 image at a time, so solution image attached below:

How comes the coin toss happens when the function isn’t even called? Is it done in another file or have I misunderstood Js all this time?

The anonymous function is invoked when the img element is parsed, thus rendering one of the indexed image files.

I see thanks! Whats the specific code showing this occurs when the img element is parsed? Or is it in the background?

@courseslayer16636
In your screenshot, you wrote
coinToss === 'heads'
whereas in your next screenshot of the solution, you can see the correct comparison
coinToss() === 'heads'
So, it isn’t a bug.