Dynamic Access

Get to know how to access members dynamically.

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, we can also access a member of an instance using the [] operator; we’ll look at yet another alternative to this in Getting and Setting Properties.

Accessing instance members

Following are the rules to access instance members:

  • 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, 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 to find all the members in an instance named instance, use the Object.keys(instance) method. This method is called keys because JavaScript considers objects to be like hashmaps, with keys and values.

Alternatively, you can iterate over the members using the for member in instance {} form.


Let’s try out these facilities with an example.

Get hands-on with 1200+ tech skills courses.