Use Variable as an Object Key in JavaScript

By James L.

In JavaScript, you can use variables as object keys when you want to dynamically define the keys for an object.

This is particularly useful for creating objects with keys that are determined at runtime or when you want to make your code more flexible.

There are two ways to use a variable as an object key in JavaScript:

1. Using Bracket Notation

Bracket notation allows you to dynamically set object keys by enclosing the variable with square brackets ([]). This is the most common and straightforward way.

For example:

// Create an empty object called 'person'
let person = {};
// Define a variable to hold the key for the person's name
let key = "name";
// Set the 'name' property of the 'person' object to "James Bond"
person[key] = "James Bond";
// Display the person object to the console
console.log(person); // { name: 'James Bond' }

WARNING: You cannot use dot notation when using a variable as a key in JavaScript. Dot notation only works with static property names. If you need to use a variable as an object key, you must use bracket notation.

For example:

let person = {};
let key = "name";

// Trying to set the 'name' property of the 'person' object to "James Bond" using dot notation
person.key = "James Bond";

console.log(person); // { key: 'James Bond' }

Even though the variable key exists, dot notation will not evaluate it when accessing the person object. This means that the person.key property will be set to the literal string ‘key’, not to the value of the key variable

2. Using Computed Property Names

Computed property names, introduced in ES6, allow you to dynamically define object keys using expressions or variables. This makes your code more concise, elegant, and readable.

However, it’s important to note that ES6 or higher compatibility is required for this feature to function properly.

For example:

// Define a variable 'key' to hold the property name
const key = "name";
// Create an object 'person' with a computed property name using 'key'
const person = {  
   [key]: "James Bond",   
   age: 37
};
// Display the person object to the console
console.log(person); // Output: { name: 'James Bond', age: 37 }

In this example, the variable key is enclosed in square brackets within the object literal. This allows you to dynamically set the object’s property name based on the value of the key variable. The result is an object with the “name” property.

Conclusion

Both methods effectively achieve the same goal of using a variable as an object key. The choice between them depends on the context and the specific version of JavaScript you’re using. 

Computed property names are more concise and elegant, but they require ES6 or higher compatibility. Bracket notation is more versatile and works with older versions of JavaScript.