# How to use computed property names in JavaScript

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Mar 4, 2021. Topics: JavaScript.
Canonical URL: https://attacomsian.com/blog/javascript-computed-property-names

> A quick guide to learn how to use computed property names to dynamically create object properties in JavaScript.

The computed property names feature was introduced in ECMAScript 2015(ES6) that allows you to dynamically compute the names of the object properties in JavaScript [object literal](https://attacomsian.com/blog/javascript-create-object#1--object-literal) notation.

A JavaScript [object](https://attacomsian.com/blog/objects-prototypes-classes-javascript#objects) is just a collection of key-value pairs called properties. A property's key is a string or symbol (also known as property name), and value can be anything.

Before computed property names, if you want to create an object with dynamic property names, you'd have to create the object first and then use bracket notation to assign that property to the value:

```javascript
const key = 'name';
const value = 'Atta';

const user = {};
user[key] = value;

console.log(user.name); // Atta
```

However, ES6 computed property names feature allows you to assign an expression as the property name to an object within object literal notation. There is no need to create an object first. 

The above code can now be rewritten like below:

```javascript
const key = 'name';
const value = 'Atta';

const user = {
    [key]: value
};

console.log(user.name); // Atta
```

The `key`  can be any expression as long as it is wrapped in brackets `[]`: 

```javascript
const key = 'name';
const value = 'Atta';

const user = {
    [key + '34']: value
};

console.log(user.name34); // Atta
```

One last thing, you can also use template literals (string interpolation) as an expression for the computed property names:

```javascript
const key = 'name';
const value = 'Atta';

const user = {
    [`${key}34`]: value
};

console.log(user.name34); // Atta
```
