Programming README

Home


Computed property names allow us to dynamically define object keys using expressions. This is done using the square bracket ([ ]) syntax inside an object literal. Computed property names can be very useful when the property name needs to be determined at runtime.

Let’s take a look at a few examples.

Computed property names are particularly useful in scenarios where you want to dynamically create property names based on certain conditions or input:

const prefix = 'user_';
const index = 1;
const user = {
  [`${prefix}${index}`]: 'Alice',
  [`${prefix}${index + 1}`]: 'Bob',
};
 
console.log(user); // Output: { user_1: 'Alice', user_2: 'Bob' }

Without computed property names, it would look like this:

const prefix = 'user_';
const index = 1;
const user = {};
 
// Add properties dynamically
user[`${prefix}${index}`] = 'Alice';
user[`${prefix}${index + 1}`] = 'Bob';
 
console.log(user); // Output: { user_1: 'Alice', user_2: 'Bob' }

Let’s look at another example, this time with TypeScript:

With computed property names

interface Config {
  [key: string]: any;
  staticProp: string;
}
 
function createConfig(dynamicProp: string, value: any): Config {
  return {
    staticProp: 'staticValue',
    [dynamicProp]: value,
  };
}
 
const config = createConfig('dynamicKey', 'dynamicValue');
 
console.log(config); // Output: { staticProp: 'staticValue', dynamicKey: 'dynamicValue' }

Without computed property names

interface Config {
  [key: string]: any;
  staticProp: string;
}
 
function createConfig(dynamicProp: string, value: any): Config {
  const config: Config = {
    staticProp: 'staticValue',
  };
  config[dynamicProp] = value;
  return config;
}
 
const config = createConfig('dynamicKey', 'dynamicValue');
 
console.log(config); // Output: { staticProp: 'staticValue', dynamicKey: 'dynamicValue' }

Benefits of Using Computed Property Names

  • Conciseness: Makes the code more concise and easier to read.
  • Dynamic Property Creation: Allows for dynamic creation of property names within the object literal.
  • Avoids Post-Object Creation Modification: Helps in avoiding modifying the object after its creation, which can be useful for maintaining immutability in certain cases.

Programming README

Home