Why quotes and square brackets with the ternary conditional operator?


#1

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....



https://www.codecademy.com/courses/react-101/lessons/react-jsx-advanced/exercises/jsx-conditionals-ternary?action=lesson_resume


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


#2

Hi,

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

 objectName.propertyName

objectName["propertyName"]

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


#3

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).


#4

Hi,

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


#5

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!


#6

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