Introduction
The es6 version of JavaScript has introduced a large variety of features that have made a huge impact on the way people write JavaScript code. In this article, we'll take a look at a new feature that came along with es6 that enables the developers to dynamically set the property keys for their objects in JavaScript.
Before ES6
Before the rise of es6, there were primarily two ways to set object keys.
- Using the dot accessor
- And using the square bracket accessor.
Using the dot accessor
The dot accessor is one of the most common ways of accessing the values from or set values into the object. The syntax to set object property using dot accessor is as follows,
- objectName.propertyKey = propertyValue;
- const user = {};
- user.firstName = 'Harshal';
The problem with the above approach is we cannot set the object keys dynamically. For example, we cannot hold the key name firstName inside a variable and then use that variable to set the key-value pair.
Using the square bracket accessor
The syntax to set object value using the square bracket accessor is as follows,
- objectName['propertyName'] = propertyValue;
- const user = {};
- user['firstName'] = 'Harshal';
- const user = {};
- const key = 'firstName'
- user[key] = 'Harshal';
- console.log(user);
- // Output: {firstName: "Harshal"}
The es6 version of JavaScript comes bundled with a solution to this problem. Now, we can use variables while creating the object to dynamically set the property.
- let key = 'firstName';
- const user = {
- [key]: 'Harshal'
- };
- console.log(user);
- // {firstName: "Harshal"}
That's it.
I hope you enjoyed this article. In case you've any feedback or queries please do let me know in the comment section.

Join the conversation! Your thoughts help the community grow.