JavaScript DOM Scripting By Example Improving the Application Code Refactor 2: Readable Branching Logic

roberto benites
roberto benites
2,897 Points

Can someone explain the "bracket" notation that s used to pass the strings? I'm not sure i fully understand how its used

in the video and code he uses the following: element[property] = value;

How are the brackets being used here? I thought brackets were used to hold arrays of objects.

1 Answer

Steven Parker
Steven Parker
177,847 Points

Brackets are used to index arrays. But they're also one of two ways to access object properties

The more common property access method is dot notation. And example would be "myobject.propname". But the same thing can be accessed with bracket notation: "`myobject['propname']". And in the example shown above, "property" is a string variable containing the property name to be accessed (since it's not a quoted string literal).

roberto benites
roberto benites
2,897 Points

Thanks! That's what i thought but was not 100% sure.

Is there a benefit to using one versus the other?

Steven Parker
Steven Parker
177,847 Points

The advantage will become obvious in the situation. Dot notation is normally more concise and convenient, but bracket notation is the only choice when the property name is not known while programming but will be supplied in a variable.