Why quotes and square brackets with the ternary conditional operator?


Can someone explain the use of the quotes and the square brackets in the ternary operator in the below piece of code from the exercise at the link? The square brackets are similar to calling an object's property, I guess. But I cannot understand why the values of the object have to be taken into the quotes....


var 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'

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



The property of an object can be accessed in two ways.



So in the above example, if coinToss() == 'heads' is true, then var img = <img src={pics['kitty']} />;
or if coinToss() == 'heads' is false then var img = <img src={pics['doggy']} />;


Hi, thanks for the reply.

I thought you need quotes only when you set a property, but then, if you get it with brackets, you need no quotes, like so:

1. var object = {};
2. object['1'] = 'value';
3. console.log(object[1]);

that's why I got a bit confused (still confused).



In order to both set and get properties of an object , you need quotes if you are using bracket notation. You can read about it here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects


Thank you very much for taking the time to reply once again. I have learned a little bit more through this. Going further with learning now. See you!


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