Computed properties
- Node.js course
- Beginner
- Lesson 67/116
- 5 min
Learn computed property names with [key].
Computed properties
Sometimes you want a property name to come from a variable or a computed expression. This is called a computed property. It is written with brackets inside the object literal.
The syntax is { [expression]: value }. The expression inside brackets is evaluated and its result becomes the property name. Example: const key = 'name'; const obj = { [key]: 'Ayşe' };. Here key holds 'name', so the object becomes { name: 'Ayşe' }.
This is useful for event names, field names from IDs, or keys coming from user input. Instead of a fixed name, you can build one dynamically.
Building a dynamic name
The power of computed properties is that the name can be any expression, not just a variable. For example ['event_' + type] appends the event type to the name. This is a common pattern in event listeners and state management.
Example: const type = 'click'; const handler = { ['on_' + type]: function () {} };. The property name becomes on_click. Instead of hardcoding it, you build it from the type variable.
The computed property syntax works only inside an object literal. To add a property later, use obj[newName] = value; this gives the same dynamic behaviour.
Practice Build an object from an event name
Let a type variable hold 'submit'. Using a computed property, define a flag object with a property named ['on_' + type] set to true. Then print that property's value with console.log.
Starter code
const type = 'submit';
// Define flag using a computed property and print its valueSample solution
const type = 'submit';
const flag = { ['on_' + type]: true };
console.log(flag['on_' + type]);Expected output
true
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the computed property parts
| Term | Meaning |
|---|---|
[key] |
Computed name |
key |
Variable holding the name |
value |
Property's value |
{ } |
Object literal |
2 Which is a computed property?
- { 'key': value }
- { key: value }
- { [key]: value } Correct answer
- { key = value }
Explanation: the expression inside brackets is evaluated.
3 Object from event name
const type = 'click';
const handler = { ['on_' + ____]: () => {}};
const type = 'click';
const handler = { ['on_' + type]: () => {}};
Explanation: 'on_' + type produces the name 'on_click'.