Computed Property Names in JavaScript

The Computed Property Name feature allows us to use an expression that returns a valid value as Property Name. We need to enclose the expression inside square brackets( []).

Dynamic Property Name

In the following example, we create a variable author and store Author Name in it.

While creating the book object, we use the author variable inside the []. The JavaScript creates the property Author Name.

This is how dynamic properties were created before ES6.

Computed Property Names

Since ES6, we can use the expression directly inside the []. The expression must return a single value. The JavaScript will evaluate the expression and uses the return value to create the property.

You can also invoke a function inside square brackets.

The following example, dynamically adds the property to object a

The addProperty takes any object and adds the property passed in its argument.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top