0
0
JavascriptHow-ToBeginner · 3 min read

How to Use Computed Property Names in JavaScript

In JavaScript, you can use computed property names by placing an expression inside square brackets [] when defining object keys. This allows you to dynamically create property names using variables or expressions within object literals.
📐

Syntax

Computed property names use square brackets [] around an expression inside an object literal. The expression is evaluated, and its result is used as the property key.

  • Expression: Can be a variable, string, number, or any expression that returns a string or symbol.
  • Object literal: The place where you define properties with keys and values.
javascript
const key = 'name';
const obj = {
  [key]: 'Alice',
  ['age']: 30,
  [1 + 2]: 'three'
};
💻

Example

This example shows how to use computed property names with variables and expressions to create dynamic keys in an object.

javascript
const prefix = 'user';
const id = 42;

const userInfo = {
  [prefix + '_id']: id,
  [prefix + '_name']: 'Bob',
  ['age']: 25
};

console.log(userInfo);
Output
{"user_id":42,"user_name":"Bob","age":25}
⚠️

Common Pitfalls

Common mistakes include forgetting the square brackets, which creates a literal key instead of a dynamic one, or using expressions that do not return strings or symbols.

Also, computed property names only work inside object literals, not when adding properties after object creation.

javascript
const key = 'score';

// Wrong: key is used as a literal property name
const wrongObj = {
  key: 100
};

// Right: use square brackets for computed property name
const rightObj = {
  [key]: 100
};

console.log(wrongObj); // { key: 100 }
console.log(rightObj); // { score: 100 }
Output
{ key: 100 } { score: 100 }
📊

Quick Reference

  • Use square brackets [] around expressions to create computed property names.
  • Expressions can be variables, string concatenations, or any expression returning a string or symbol.
  • Computed property names work only inside object literals.
  • Without brackets, keys are treated as literal strings.

Key Takeaways

Use square brackets around expressions to create dynamic object keys in JavaScript.
Computed property names allow variables and expressions as keys inside object literals.
Without brackets, keys are treated as fixed literal strings, not dynamic values.
Computed property names only work when defining objects, not when adding properties later.
Expressions inside brackets must return strings or symbols to be valid keys.