"JSX Conditionals: If Statements That Do Work"


#1

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.


#2

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


#3
// 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']} />;

#4

here:

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.


#5

Break this down to its elementary parts…

<img src=... />

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

src={...}

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

pics[key]

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']} />

or,

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

which of course resolves to ,

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

or,

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

#6

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