Accessing Object Properties with Variables - bracket

Tell us what’s happening:
I cannot explain why I have to use the bracket notation in
var player = testObj[playerNumber];

in the first tentative, I have used parenthesis, and it doesn’t work (obvious!). But why I have to use brackets? is there any additional concept, or should I just remember it by heart?

Many many 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 Lin

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0 Safari/605.1.15.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/accessing-object-properties-with-variables

in a very simplified way, I will have parenthesis in functions to create actions, while I will have to use brackets to point or reference? could it be said in that way?
Many thanks!

Whenever you use dot notation, it looks for property within your object, so:

const obj = {
  a: 1,
  b: 2,
  c: 3
};

const a = 'b';

console.log(obj.a) // 1
console.log(obj[a]) // 2
console.log(obj['a']) // 1

// ...so:
obj.a === obj['a'];
obj.a !== obj[a];
1 Like