Accessing Object Properties with Variables *QUESTION*

I passed the test but I have a question:
Why would I store my property in a variable to look it up? It’s not passing with just
var player = testObj[16]; ? If the property 16 can be recognized and stored as a variable, why can’t I just store the result of the test in var player and return that? Is it because something isn’t being returned that way? Thanks!

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

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36.

Challenge: Accessing Object Properties with Variables

Link to the challenge:

You won’t always be able to hard code in the exact value that you will always want in your code. It’s the same reason that you use any variable.

1 Like

it normally does work but …
in this particular exercise the test needs playerNumber to be 16 in order to pass.

the challenge is meant trying to teach you how to use variables.

// Variables let you edit values in many places at once

// Avoid
square(5);
isOdd(5);

// Preferred
let num = 5; 
square(num);
isOdd(num);
1 Like

I was suspicious that it was because the test itself needs playerNumber to be 16 as a requirement. So you can put a property of an object to a variable with the name of your choice and use that variable as that property basically?

Yeah. So in this case, you could get handed some variable that contains a player number and you want to find the player that matches. Then you’d use that last line of your code to do just that.

Example:

function getPlayer(players, playerNumber) {
  return players[playerNumber];
}
1 Like