How to use computed property names 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 notation.

A JavaScript object 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:

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:

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 []:

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:

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

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

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

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.