2

I don't know how to read this piece of code:

var byName = {};
ancestry.forEach(function(person){ byName[person.name] = person;]);
console.log(byName["Phil"]);

What I'm confused about is the "byName[person.name] = person" part of the code.

1) what does byName[person.name] mean? Why is square bracket notation used and not a dot notation?

2) Why is it equated to person (byName[person.name] = person) and how does that work?

ps: ancestry is a JSON file as a string that's available in the sandbox of my ebook.

2 Answers2

2

Dot notation uses an identifier. x.foo gets the foo property.

Square bracket notation takes a string. x["foo"] gets the foo property.

The string can come from any expression.

var person = {};
person.name = "foo";
x[person.name]

… gets the foo property

byName[person.name] = person; just breaks down to "Create a new property named after the current person on the byName object and make its value the current person object"

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
2

This code loops through ancestry and adds to the object byName. The byName[person.name] = person is adding a new element to the byName object. The key is the person.name and the set value is the person. In other words, this code allows a way to quickly lookup a person object from it's name. The last line of code demonstrates this in action.

sekimm2
  • 94
  • 3