Computed property names allow us to dynamically define object keys using expressions. This is done using the square bracket ([ ]) syntax inside an object literal. Computed property names can be very useful when the property name needs to be determined at runtime.
Let’s take a look at a few examples.
Computed property names are particularly useful in scenarios where you want to dynamically create property names based on certain conditions or input:
Without computed property names, it would look like this:
Let’s look at another example, this time with TypeScript:
With computed property names
Without computed property names
Benefits of Using Computed Property Names
Conciseness: Makes the code more concise and easier to read.
Dynamic Property Creation: Allows for dynamic creation of property names within the object literal.
Avoids Post-Object Creation Modification: Helps in avoiding modifying the object after its creation, which can be useful for maintaining immutability in certain cases.