Dynamic Access
To access a field, a property, or a method, we use the dot notation in JavaScript much like in languages like Java, C#, and many other languages. However, in addition, we can access a member of an instance using the [] operator—we’ll look at yet another alternative to this in Getting and Setting Properties.
Use the dot notation, like sam.age or sam.play(), if you know the member name at code writing time. If the member name is not known until runtime, then use the [] notation. Suppose variables named fieldName and methodName contain the name of a field and a method—for example, "age" and "play", respectively. Then sam[fieldName] is equivalent to writing sam.age and sam[methodName]() is like writing sam.play().
If you’re curious ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access