Accessing Object Properties with Variables lesson

Tell us what’s happening:
For this example it says to use a string , unless I am mistaken a string must contain single or double quotes, yet if you use those it fails. When you remove the quotes it passes this lesson. am I mistaken or does this lesson need correcting to pass? I put my code below.

Your code so far


// Setup
var testObj = {
12: "Namath",
16: "Montana",
19: "Unitas"
};

// Only change code below this line

var playerNumber = 16;       // Change this line
var player = testObj["playerNumber"];   // Change this line <--- says incorrect

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.67 Safari/537.36.

Challenge: Accessing Object Properties with Variables

Link to the challenge:

Hey @cyberionsentry!

Welcome to the forum!

FCC instructions:
Note that we do not use quotes around the variable name when using it to access the property because we are using the value of the variable, not the name .

So the instructions don’t say to use a string but rather you are trying to access the value.

So when playerNumber equals 16 this is what is happening with the code

testObj[playerNumber]

// is interpreted  like this
testObj[16]

The computer is looking at an object called testObj and accessing the value of testObj[16] which happens to be a string called “Montana”.

That is why you don’t need to wrap playerNumber in a string.

Does that make sense?

Thank you jwilkins for helping me understand that. It makes sense the way you explain it.

1 Like