1

I'm curious about this line and have never seen this format with an array right after the variable:

pics[coinToss() === 'heads' ? 'kitty' : 'doggy'] to render pics.doggy or pics.kitty

Is there specific documentation about this format I can read more about?

import ReactDOM from 'react-dom';

function coinToss () {
  // Randomly return either 'heads' or 'tails'.
  return Math.random() < 0.5 ? 'heads' : 'tails';
}

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

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

ReactDOM.render(
    img, 
    document.getElementById('app')
);
Miko
  • 503
  • 3
  • 9

1 Answers1

2

It's not an array, it's a property access - like when you access some array's elements with myArray[5] to get the 6th element (which is property 5 of the array), but it works the same for string properties of objects: pics['kitty'] is the same as pics.kitty.

The name of the property accessed is whatever coinToss() == 'heads' ? 'kitty' : 'doggy' evaluates to (which uses ?: to yield either 'kitty' or 'doggy' depending on the result of coinToss()).

Here it's functionally the same as coinToss() === 'heads' ? pics.kitty : pics.doggy.

CherryDT
  • 25,571
  • 5
  • 49
  • 74