Accessing Object Properties with Variables: Why we need it

I think I don’ t understand why we need to access the value of a property for an object via variable in the following way:

var testObj = {
  12: "Namath",
  16: "Montana",
  19: "Unitas"

var playerNumber = 16;       // Change this Line
var player = testObj[playerNumber];   // Change this Line

When we could do it like this directly:

var player =  testObj["16"];, for example.

In the lesson, it is said: " This can be very useful for iterating through an object’s properties or when accessing a lookup table."

But I don’t quite understand what it means. Could you give an easy example if possible?

My browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:69.0) Gecko/20100101 Firefox/69.0.

Link to the challenge:

Hello @nastya,

You definitely can access object properties with keys directly, but often you won’t know that exact key name. For example, when looping through the object, you will use an additional variable like “playerNumber”.

Also, it is a good idea to always give descriptive names, so other developers can easily read your code. In your case - testObj["16"] - you hardcoded the key which is not ideal and for me, for example, value “16” means nothing, but when testObj[playerNumber] - it gives me understanding what I will get back as a value.

Hope it will help you :slight_smile:

1 Like

Imagine that, what if this value is dynamic, and you don’t know value of this variable ?

1 Like

As examples for above two answers:

Maybe I want to loop through the object and do something:

for (const key of Object.keys(testObj)) {

Or maybe I have some function that grabs properties from an object

function getPropertyAndDoSomething(obj, key) {

I can’t hardcode the names of the keys because I don’t know what they are

1 Like