Using Variables as Object Keys in JavaScript

Mateen Kiani

Mateen Kiani

Published on Tue Jul 01 2025·4 min read

using-variables-as-object-keys-in-javascript

Introduction

JavaScript objects are powerful data structures that let you store key–value pairs. Typically, we use hard-coded strings as keys. But what if you need the property name to come from a variable? This is common when building flexible data models or handling dynamic data.

Using variables as keys can be tricky at first glance. You might try writing let obj = { keyVar: value } only to get a property literally named "keyVar". How do you insert the content of the variable instead? In this article, we'll explore computed property names, bracket notation, and best practices to make your code clear and bug-free.

Why Dynamic Keys Matter

Dynamic keys let you adapt your object’s shape based on runtime data. For example, you might parse JSON from an API and want to rename fields or combine multiple data sources into one single object. Without variable keys, you’d be stuck writing repetitive code or awkward if statements.

Dynamic keys are also helpful in scenarios like form builders, event trackers, or localization systems. In each case, you want your code to read the variable name and use it as the property name. This pattern keeps your code DRY (Don’t Repeat Yourself) and more maintainable.

Tip: If you’re new to objects, check out this JavaScript Object Guide to get the basics.

Computed Property Names

Introduced in ES6, computed property names let you define dynamic keys right inside object literals. You wrap the variable in square brackets:

let propName = 'username';
let user = {
[propName]: 'alice',
age: 30
};
console.log(user.username); // alice

Here, propName is evaluated at runtime and used as the key. You can also use expressions:

let index = 1;
let settings = {
['option_' + index]: true
};
console.log(settings.option_1); // true

Computed names work for any expression, including function calls or template literals. This is the cleanest way to create objects with variable keys.

Bracket Notation for Assignment

If you need to add or update a property after the object is created, bracket notation is your friend:

let obj = {}; // start with an empty object
let keyVar = 'score';
let value = 95;
obj[keyVar] = value;
console.log(obj.score); // 95

You can also use this in loops:

let data = ['a', 'b', 'c'];
let result = {};
data.forEach((item, idx) => {
result[`item_${idx}`] = item;
});
console.log(result); // { item_0: 'a', item_1: 'b', item_2: 'c' }

Bracket notation is essential whenever the key is not a literal. It also supports nested properties:

let path = 'settings.theme';
let parts = path.split('.');
let deep = {};
let current = deep;
parts.forEach((p, i) => {
if (i === parts.length - 1) {
current[p] = 'dark';
} else {
current[p] = {};
current = current[p];
}
});
console.log(deep.settings.theme); // 'dark'

Variables in Object Literals

Beyond simple keys, you can use variables for both keys and values in object literals:

let dynamicKey = 'color';
let dynamicValue = 'blue';
let palette = {
[dynamicKey]: dynamicValue
};
console.log(palette.color); // 'blue'

You can mix computed names and traditional properties. This pattern shines in factory functions:

function makeConfig(key, val) {
return {
id: Date.now(),
[key]: val,
created: new Date()
};
}
let cfg = makeConfig('timeout', 5000);
console.log(cfg.timeout); // 5000

This approach reduces boilerplate and makes your code adaptable to new requirements.

Practical Tips and Pitfalls

• Always verify that your variable holds a string or symbol. If it’s undefined or null, you’ll get an unintended key like "undefined".

• Avoid using user input directly as keys. Malicious or malformed keys can lead to unexpected behavior.

• Remember that object keys are always strings or symbols. Numbers are converted to strings:

let numKey = 42;
let obj = { [numKey]: 'value' };
console.log(obj['42']); // 'value'

• Computed property names cannot be used in older environments without transpiling. If you need IE11 support, consider using bracket notation after object creation.

Tip: Run your code through a linter like ESLint. It can catch typos in variable names or accidental use of undeclared variables.

Real-World Use Cases

  • Form handlers:

    function handleInput(name, val) {
    return { [name]: val };
    }
  • API response mappers:

    let fields = ['firstName', 'lastName'];
    let user = {};
    fields.forEach(f => user[f.toLowerCase()] = apiData[f]);
  • Event logs:

    let log = {};
    function event(key, data) {
    log[key] = data;
    }
    event('click', { x: 10, y: 20 });

These examples show how variable keys streamline code when dealing with dynamic data shapes.

Conclusion

Using variables as object keys in JavaScript unlocks a new level of flexibility and DRY coding. By mastering computed property names and bracket notation, you can dynamically shape objects, map data, and build reusable utilities. Always check your variable’s value before using it as a key, and consider security implications when dealing with user input. Practice these patterns to write cleaner, more maintainable code.

Dynamically choosing your object’s keys makes complex data handling simpler. Keep these tips close, and you’ll avoid common pitfalls while building adaptable JavaScript applications.


Mateen Kiani
Mateen Kiani
kiani.mateen012@gmail.com
I am a passionate Full stack developer with around 3 years of experience in MERN stack development and 1 year experience in blockchain application development. I have completed several projects in MERN stack, Nextjs and blockchain, including some NFT marketplaces. I have vast experience in Node js, Express, React and Redux.