Skip to content
jshacks.dev
Fundamentals

Computed Property Names and Shorthand Syntax in JavaScript

Computed property names build object keys from expressions, and shorthand writes a name once. See key coercion, ordering and the proto exception.

8 min read
Summarize in AI
Flat illustration of an editor window full of code, with the JavaScript, Node.js, TypeScript and npm logos.

An object literal that looks up its own key from a variable is the most common reason people learn computed property names, usually at the moment a form handler needs { [event.target.name]: event.target.value }. The syntax is small and has three layers: shorthand for names that already exist as variables, method shorthand for functions, and brackets for keys built at runtime. Each layer has a rule that is easy to state and easy to trip over. This post covers them in order, shows the coercion and ordering rules with output from Node.js 24, and ends with the one key that behaves differently. It builds on the post on objects, and the spread syntax used in the update patterns is in the post on spread and rest.

Property shorthand

When the key and the variable have the same name, write it once.

JavaScript
const name = "Ada";
const visits = 3;
const role = "admin";

const verbose = { name: name, visits: visits, role: role };
const short = { name, visits, role };

console.log(short);
console.log(JSON.stringify(verbose) === JSON.stringify(short));

function createUser(name, role = "viewer") {
  return { name, role, createdBy: "system" };
}

console.log(createUser("Grace"));
Text
{ name: 'Ada', visits: 3, role: 'admin' }
true
{ name: 'Grace', role: 'viewer', createdBy: 'system' }

Both objects are identical. Shorthand reads best when the variable names are already the field names, which is why it is common in return statements and in code that builds a payload from local variables. It mixes freely with regular entries, as createdBy shows.

Method shorthand

Writing a function as a method drops the function keyword and the colon.

JavaScript
const counter = {
  count: 0,
  increment() {
    this.count += 1;
    return this.count;
  },
  async load() {
    return "loaded";
  },
  *ids() {
    yield 1;
    yield 2;
  },
};

console.log(counter.increment());
console.log(counter.increment.name);
console.log([...counter.ids()]);

const oldStyle = {
  increment: function () {
    return 1;
  },
};

console.log(oldStyle.increment.name);
Text
1
increment
[ 1, 2 ]
increment

Methods can be async and generators with a leading async or *. A method gets a name from its key, and so does a function expression assigned to a key, so the two look similar in output. The difference is in what the language allows. A method defined with shorthand can use super, which looks up a property on the object's prototype, and it cannot be used as a constructor with new, where an old-style function can.

JavaScript
const base = {
  describe() {
    return "base";
  },
};

const derived = {
  __proto__: base,
  describe() {
    return "derived over " + super.describe();
  },
};

console.log(derived.describe());

try {
  new derived.describe();
} catch (error) {
  console.log(error.name + ": " + error.message);
}
Text
derived over base
TypeError: derived.describe is not a constructor

super.describe() works inside the shorthand method because the engine records the home object. The attempt to call it with new fails with a clear message. An arrow function stored under a key has neither feature and no this of its own, so use method shorthand for object methods, as the post on the this keyword recommends.

Computed property names

Square brackets in a literal key evaluate an expression, and the result becomes the property key.

JavaScript
const field = "email";
const prefix = "user";
let counter = 0;

const form = {
  [field]: "[email protected]",
  [`${prefix}Id`]: 42,
  ["a" + "b"]: true,
  [1 + 1]: "two",
  [Symbol.for("meta")]: "symbol key",
  [`slot-${++counter}`]: "first",
  [`slot-${++counter}`]: "second",
};

console.log(form);
console.log(counter);
Text
{
  '2': 'two',
  email: '[email protected]',
  userId: 42,
  ab: true,
  'slot-1': 'first',
  'slot-2': 'second',
  Symbol(meta): 'symbol key'
}
2

Any expression is allowed: a variable, a template literal, concatenation and even an increment. The number key 2 was converted to the string "2" and sorted with the integer keys first, a rule from the post on objects. The two slot keys were evaluated left to right, so counter ended at 2, and each key got its own value. The expression is evaluated once, when the literal runs.

The same brackets work in classes, for methods and fields.

JavaScript
const action = "reset";
const kind = Symbol("kind");

class Store {
  value = 0;
  [action]() {
    this.value = 0;
    return "reset done";
  }
  [`get${"Value"}`]() {
    return this.value;
  }
  static [kind] = "store";
}

const store = new Store();
console.log(store.reset());
console.log(store.getValue());
console.log(Store[kind]);
Text
reset done
0
store

The form handler pattern

The common use is updating one field of a state object from a key held in a variable. With computed names and spread, the update is one expression and never mutates.

JavaScript
const state = { name: "Ada", email: "" };

function update(current, event) {
  return { ...current, [event.name]: event.value };
}

const next = update(state, { name: "email", value: "[email protected]" });
const nested = {
  ...next,
  tasks: { ...next.tasks, ["t-" + 7]: { done: true } },
};

console.log(state);
console.log(next);
console.log(nested);
Text
{ name: 'Ada', email: '' }
{ name: 'Ada', email: '[email protected]' }
{
  name: 'Ada',
  email: '[email protected]',
  tasks: { 't-7': { done: true } }
}

The original state was not changed, and next holds a new object with one key replaced. The nested version builds a keyed collection of tasks, which is the shape state libraries use for lookup by id. Validate event.name against a known list first, because a computed key from untrusted input can write any property, including ones you did not expect.

Well-known symbols need brackets

The language's hooks are symbol-keyed properties, and a symbol can only be written as a key with brackets. That is how a plain object becomes iterable, or controls its own conversion.

JavaScript
const range = {
  from: 1,
  to: 4,
  *[Symbol.iterator]() {
    for (let n = this.from; n <= this.to; n++) yield n;
  },
  [Symbol.toPrimitive](hint) {
    return hint === "string" ? `${this.from}..${this.to}` : this.to - this.from;
  },
};

console.log([...range]);
console.log(`${range}`);
console.log(range * 2);
console.log(String(range[Symbol.iterator].name));
Text
[ 1, 2, 3, 4 ]
1..4
6
[Symbol.iterator]

The generator method is declared with both the * marker and a computed key, so one line adds iteration. The conversion hook returns a string for template literals and a number for arithmetic, a mechanism explained in the post on converting objects to primitives. The last line shows that a computed method gets a descriptive name built from the symbol, which appears in stack traces and helps debugging.

Naming functions with computed keys

A function stored under a computed key takes its name from the key, which affects stack traces and the name property. For a dynamic key, the name is the key's string value at creation time.

JavaScript
const verb = "save";

const api = {
  [verb + "Draft"]() {},
  [verb + "Final"]: () => {},
  [Symbol("audit")]() {},
};

console.log(api.saveDraft.name, api.saveFinal.name);
console.log(Object.getOwnPropertySymbols(api).map((s) => api[s].name));
Text
saveDraft saveFinal
[ '[audit]' ]

The names follow the keys, and a symbol key produces a name in square brackets. That detail rarely matters, but a stack trace showing [audit] instead of an anonymous function is easier to read, and logging libraries that group by function name benefit.

Duplicates and order

When a key appears twice, the last one wins, and the property keeps the position of its first occurrence.

JavaScript
const key = "mode";

const result = {
  mode: "light",
  [key]: "dark",
  other: 1,
  ["mo" + "de"]: "contrast",
};

console.log(result);
console.log(Object.keys(result));

const defaults = { retries: 3, timeout: 100 };
console.log({ ...defaults, timeout: 500 });
console.log({ timeout: 500, ...defaults });
Text
{ mode: 'contrast', other: 1 }
[ 'mode', 'other' ]
{ retries: 3, timeout: 500 }
{ timeout: 100, retries: 3 }

All three mode entries collapsed into one, holding the last value, and it stayed first in the order. The two spread lines show why order matters: values written after the spread override it, and values written before are overridden by it. Putting defaults first and overrides last is the usual shape.

The __proto__ exception

A literal key written exactly as __proto__ sets the object's prototype, and a computed key ["__proto__"] creates a normal own property, the difference being a security detail.

JavaScript
const withPrototype = { __proto__: { inherited: true }, own: 1 };
const withComputed = { ["__proto__"]: { inherited: true }, own: 1 };

console.log(withPrototype.inherited, Object.hasOwn(withPrototype, "__proto__"));
console.log(withComputed.inherited, Object.hasOwn(withComputed, "__proto__"));
console.log(Object.keys(withPrototype), Object.keys(withComputed));
Text
true false
undefined true
[ 'own' ] [ '__proto__', 'own' ]

The first object inherited inherited through its new prototype and has no own __proto__. The second stored an ordinary property named __proto__, with no inheritance. Computed keys therefore avoid the prototype setter, which makes them the safer way to build an object from untrusted key names, though an object from Object.create(null) or a Map is safer still.

Reading code that uses them

Three habits make dense literals readable. Keep a computed key to a single short expression, and move anything longer into a named variable above the object. Put shorthand entries together, so a reader can see at a glance which fields come from local variables and which are written out. And when a literal mixes spread, computed keys and overrides, add a comment line saying which wins, since order is the whole meaning. A literal that needs a paragraph of explanation is usually doing two jobs and should be two statements.

Where these features stop

Shorthand and computed names do not apply to destructuring targets in the same way. In a destructuring pattern, a computed key reads a property, and a rename uses a colon, as covered in the post on destructuring. Computed keys cannot be used to create a getter with a dynamic name in a way that appears in a stack trace, since the function name is only a label.

If a key is built from user input, check it against an allow-list before using it, and prefer a Map for open-ended keys. And do not use computed names to hide an object's shape: a reader looking for user.email cannot find where it was defined if it came from a variable three files away.

The syntax is defined in the specification under object initializer, and MDN's object initializer reference covers shorthand, methods and computed names.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.