How to Add Dynamically Named Properties to Objects in JavaScript

One of the great features of ES6 is computed property names.

Let's say we have the following properties:

const a = 'age';
const j = 'j';

And a person object:

const person = {
  firstName: 'John',
  lastName: 'Doe',
  [a]: 25,
  [`${j}ob`]: 'Software Developer'
};

As long as we have brackets around our expressions, these expressions will be dynamically translated into the string used as the key.

This includes template literals and string concatenation.

If we now log the person object, we would get the following result:

{
  firstName: 'John',
  lastName: 'Doe',
  age: 25,
  job: 'Software Developer'
}

This method can also be used in functions without the need of creating an object!

Passing in the two properties into our createPerson function gives the same result:

const createPerson = (a, j) => {
  return {
    firstName: 'John',
    lastName: 'Doe',
    [a]: 25,
    [`${j}ob`]: 'Software Developer'
  }
};