"JSX Conditionals: If Statements That Do Work"

How is it that ‘coinToss’ does not have to be executed/ran, as in coinToss(), for the function to work?
Does putting the function in ‘if statement’ automatically run the function? Because, that’s what it seems like.

Function always have to be called in order to execute

Please share your code and exercise url so i can find the exercise and run code, so i can have a look and explain it further

// Function is declared below.
function coinToss () {
  return Math.random() < 0.5 ? 'heads' : 'tails';

const pics = {
  kitty: 'https://s3.amazonaws.com/codecademy-content/courses/React/react_photo-kitty.jpg',
  doggy: 'https://s3.amazonaws.com/codecademy-content/courses/React/react_photo-puppy.jpeg'

// Below is a ternary form of 'if statement'. I don't see a function being executed. Is it executed once it goes inside the condition brackets?
const img = <img src={pics[coinToss() === 'heads' ? 'kitty' : 'doggy']} />;


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

there is a function call on this line (coinToss())? I don’t see a problem, the result of the function call is used in the ternary operator.

Break this down to its elementary parts…

<img src=... />

is JSX stored as an ES global constant, const img = ....


An unquoted React.js expression declared in the src attribute value.


An object earlier defined with two keys, ‘kitty’, and ‘doggy’. Their values are URI’s to associated images.

coinToss() === 'heads'

A boolean expression that compares the return value of a call to coinToss to a string literal. This boolean is the conditional, one of three parts to a ternary expression.

coinToss() === 'heads' ? 'kitty' : 'doggy'

Depending upon the boolean, if True, kitty will be the key used, else doggy is used.

In simplified form, we get…

<img src={pics['kitty']} />


<img src={pics['doggy']} />

which of course resolves to ,

<img src="https:// ... /react_photo-kitty.jpg" />


<img src="https:// ... /react_photo-puppy.jpg" />

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