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