Basic JavaScript - Accessing Object Properties with Variables

This is a dumb question, but when you are assigning the variable: playerNumber to 16, how does it know playerNumber is referring to a property in testObj? How are those two correlated by just assigning 16 to it? I looked back into global/local scope and still couldn’t wrap my head around it. Thanks in advance.

Your code so far

// Setup
const testObj = {
  12: "Namath",
  16: "Montana",
  19: "Unitas"

// Only change code below this line
const playerNumber = 16;  // Change this line
const player = testObj[playerNumber];   // Change this line

Challenge: Basic JavaScript - Accessing Object Properties with Variables

Link to the challenge:

testObj[playerNumber] evaluates the playerNumber variables and uses the value as the key.

const user = {
  name: 'John',
  age: 42

const key = 'name';
console.log(user[key]) // John
console.log(user['age']) // 42
1 Like

Thank you immensely.

I don’t really understand why it is doing it. Why isn’t it just another const with the value 16?

Are you asking why you would use a variable instead of a literal value? If so, you will see more examples of using variables with object access later in the curriculum.

There are various reasons why you might need to use a variable, one such being you might not know ahead of time what value you need to use (dynamic runtime access).

That wasn’t my question, but very interesting point.

I wondered, like in the the original post:

but I guess it musst be the


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