Basic JavaScript - Accessing Object Properties with Variables

Tell us what’s happening:
Describe your issue in detail here.
whats the use of using variables to acess object properties when we can use 1. Dot property accessor: object.property and 2. Square brackets property access: object['property']?? Please do explain

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


  **Your browser information:**

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

Challenge: Basic JavaScript - Accessing Object Properties with Variables

Link to the challenge:

Dot notation and bracket with a literal string like that are only good when you know exactly what properties you are looking for and you are going to hard code that in (you should try not to hard code). Using a variable your code can be more dynamic and cleaner.

const object = { a: 1, b: 2, c: 3, d: 4, e:5 , f:6 , g:7, h:8};

for (const property in object) {
  console.log(object[property]);
}

This is a type of loop you will learn later. Imagine having to hard code the entire alphabet to get all the values in these properties if it didn’t stop at the letter h. But with variables its much simpler, cleaner and can handle someone adding or changing the properties.

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