Explain Codes LogoExplain Codes Logo

How to use a variable for a key in a JavaScript object literal?

javascript
prompt-engineering
functions
callbacks
Anton ShumikhinbyAnton Shumikhin·Feb 22, 2025
TLDR

To assign a key to a JavaScript object dynamically, utilize the computed property names feature by using square brackets [ ]:

let propName = 'name'; let obj = { [propName]: 'Alice' // Now you're talking! }; console.log(obj.name); // Outputs: 'Alice'

This approach was introduced in ECMAScript 2015 (ES6) and allows for more dynamic code, making it ideal for cases envolving variable data.

ES6: A step to dynamic object literal keys

The old way: ES5 and earlier

Before ES6, if you wished to use a key from a variable, it required a bit more patient maneuvering:

var oldKey = 'oldSchool'; var oldObj = {}; oldObj[oldKey] = 'Not bad!'; // Bingo, but a bit old school, isn't it?

The new way: Welcome ES6

ES6 brought along a cool new feature: computed property names. You can now set property keys dynamically directly in the object literal:

let dynamicKey = '.Dynamic'; let newObj = { [dynamicKey]: 'Now, we are dynamic!' };

Now, doing newObj['.Dynamic'] gets you 'Now, we are dynamic!'. Magic? No, it’s JavaScript!

Various flavors of property keys

ES6 gave us several options to name property keys:

  • String: { "myKey": "Gotcha!" }
  • Number: { 404: "Error" } // Where did the page go?
  • Identifier: { validIdentifier: "Fine by me!" }
  • Template literals: {[`Key_${expression}`]: "I'm a mix!"}

The power of dynamic keys

Animating things dynamically

With animate and similar functions, dynamic property names can bring your animations to life:

function animate(element, prop, value) { let animation = { [prop]: value // Dancing to the beat of 'value' }; // Animation magic happens next... }

CSS on the go

Imagine changing CSS properties for DOM elements dynamically:

let cssProperty = 'color'; let cssValue = 'red'; element.style[cssProperty] = cssValue; // And it's RED! Just like that.

This makes for more responsive and interactive user experiences.