Course contentsShow
← JavaScript
Lesson 618 of 2,72315. ObjectsFree lesson

Computed Keys from Variables

Use variables to determine property names, enabling flexible object creation patterns.

Computed Keys from Variables

What You'll Learn: How to use variables to dynamically set property names in object literals, making your object creation flexible and powerful.

The Core Idea

You've seen computed property names using expressions in square brackets like [someExpression]. Now we focus specifically on using variables as those expressions. This lets you decide property names at runtime based on program state, user input, or any other dynamic data.

Instead of hardcoding property names, you store the desired key in a variable and let JavaScript use that variable's value as the property name.

How It Works

const propertyName = 'username';

const user = {
  [propertyName]: 'alice_dev'
};

console.log(user); // { username: 'alice_dev' }
console.log(user.username); // 'alice_dev'

The variable propertyName holds the string 'username', so that becomes the actual property key in the object.

Practical Example: Flexible Object Creation

const fieldName = 'status';
const fieldValue = 'active';

const record = {
  id: 101,
  [fieldName]: fieldValue
};

console.log(record); // { id: 101, status: 'active' }

This pattern is especially useful when building objects from configuration, form data, or API responses where you don't know property names ahead of time.

Multiple Dynamic Keys

const key1 = 'firstName';
const key2 = 'lastName';

const person = {
  [key1]: 'Maya',
  [key2]: 'Chen'
};

console.log(person); // { firstName: 'Maya', lastName: 'Chen' }

Each variable independently determines its property name.

Key Takeaway: Using variables in square brackets [variable] lets you create objects with property names determined at runtime, enabling flexible, data-driven object construction patterns.