I am trying to understand something very basic. If I have an object like this:
var topics = {}
And I do this:
topics[name] = ["chapter 1", "chapter 2", "chapter 3"];
When I log this object, I don’t see the name attribute. What have I done exactly? Have I created a key called name with the value of an array?
Of course I know I can do that by just doing
topics.name = ["chapter 1", "chapter 2", "chapter 3"];
But then what is this doing?
topics[name] = ["chapter 1", "chapter 2", "chapter 3"];
Could someone please clarify?
When you use the
[]notation it expects an expression in between, that translates to a string.Using
namenot enclosed in quotes'name'it assumes you are using a variable called name.Which in your case is
undefined.The correct usage would be
If you want to use a variable you can do things like
this will create the
nameproperty on the object.. useful for dynamic/automatic creation/filling of objects..