JS in JSX for newbie
Hello!
What is the square brackets in the
const img
doing here:
Are they allowing for the ternary function to choose the pics
property and connecting them to coinToss()
in an array?12 Replies
It's picking a key from the object
pics
. The key is determined by the ternary operator. When in doubt, break things down starting from the most outwards expression:
When using bracket notation on an object, you extract the value stored using that key from the object. It's the same as with array index, except arrays use numbers only where as object use keys which are arbitrary strings.Now I'm really confused ...
I just finished the lesson on
key
, and don't understand how keys are part of this when there is no key
keyword to be seen in the code ...
oooooohh .... i just got it!!!
key: value ...
right?Glad you did š I was just about to say you shouldn't be going over React if you don't understand this basic concept š
That's right.
If you think of an array:
0: some data
1: some more data
2: more data
It's numbers. And you use bracket notation to access it right:
array[2] // returns 'more data'
Makes sense?
With objects you don't use numbers but strings.
obj:
key1: value
key2: value2
So, obj[key2]
returns "value2"Yep! It really is a matter of just writing and reading code. I got blind sided by the function
coinToss()
being inside the array in const img
.It's not the prettiest way to write it, no.
But as I said when in doubt start reading from the end and breaking down all the expressions.
What would be a cleaner way to write it, if I may ask? In this part codecademy is really focusing on the use of ternary operator ...
Well, giving it's React I would also like to avoid having another variable just for the coin toss... but maybe this would help a bit:
Just an example, it's something subjective I guess
I mean, we've obviously discussed this issue, but that code does make more sense to me. The
heads
is, for a newbie as me, just more syntax that my brain must decode ...
Now it's more obvious that we're going straight to the objects in pics
.
I might have still needed the double take to land the key
issue, but as I said ā it's less syntax to decipher.In courses and tutorials it's normal to be more explicit to make things clearer. I guess it doesn't always work out that way, but the good thing is that once you get it you understand all the parts involved in that code.
Indeed!
Thanx a mills for the help to dig the answer out ...
š
No worries, best to ask when you're in doubt š
[ coinToss() === 'heads' ? 'kitty' : 'doggy' ] here coinToss() return the string object and this object should be equal to the 'heads' and his datatype should be same if it is true then he will return kitty picture url otherwise doggy and here used conditional operator ok