Defining Computed Members

Dynamic names for class members

Sometimes, we like to give dynamic names to members of a class, that is, to fields, properties, and methods. The approach to achieve this is also useful as a workaround to provide arbitrary names for members, bypassing the language’s restriction on making members with only alphanumeric characters.

Recall using special method names like Symbol.search and Symbol.iterator in Symbol.search and Implementing an Iterator respectively. Writing a method named Symbol.iterator() {} will result in an unexpected token error. We have to place it within [], like so: [Symbol.iterator]() {}.

Creating a computed property

To create a computed property, we place a variable containing the name of the property as the value in []. Alternatively, we can place a string or a template literal within [].

Let’s explore this with an example.

Get hands-on with 1200+ tech skills courses.