Dot vs Brackets in "Accessing Object Properties with Variables"

Tell us what’s happening:

For this exercise :

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

I notice that this works:
var player = testObj[playerNumber];

but that this does NOT:
var player = testObj.playerNumber;

Why does the dot not work here?


// 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
  **Your browser information:**

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0.2 Safari/605.1.15.

Challenge: Accessing Object Properties with Variables

Link to the challenge:

Dot notation can only be used with the exact literal name of the property. If the name of the property is instead stored in a variable, then you must use bracket notation.

1 Like

Super helpful and clear explanation. Thanks, Jeremy!

1 Like

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