Skip to content

Object shorthand: concise properties and methods (ES2015)

  • How shorthand properties ({ orderId }) and shorthand methods (getOrder() {}) are defined.
  • What makes a shorthand method different from a function property: super, no prototype, not constructible.
  • The edge cases: undeclared names, reserved words, __proto__, and value snapshots.
  • When shorthand is the wrong tool, for example when you need an arrow function’s this.

TL;DR: inside an object literal, { orderId } means { orderId: orderId }, and describe() { ... } defines a method without writing function. Both arrived in ECMAScript 2015 together with computed property names. Shorthand methods are not just shorter: they can call super, and they cannot be used with new.

Before ES2015, building an object from local variables meant writing every name twice, and every method needed the function keyword. Payloads, module exports and factory results repeated the same identifiers line after line.

Running the samples: save each complete sample as a .mjs file and run it with Node.js 22 (node sample.mjs). The output shown under each sample was produced with Node.js 22.23.

const orderId = 'ord-1042';
const customerId = 'cus-77';
const total = 129.5;
// Before ES2015: every name written twice, every method spelled out.
const oldPayload = {
orderId: orderId,
customerId: customerId,
total: total,
describe: function () {
return this.orderId + ' for ' + this.customerId;
},
};
// ES2015: shorthand properties and a shorthand method.
const payload = {
orderId,
customerId,
total,
describe() {
return `${this.orderId} for ${this.customerId}`;
},
};
console.log(payload.describe());
console.log(JSON.stringify(payload) === JSON.stringify(oldPayload));

Output:

ord-1042 for cus-77
true

A shorthand property is an identifier on its own. The engine reads the binding with that name and creates an ordinary property with the same name and its current value, exactly like orderId: orderId.

A shorthand method is a MethodDefinition in the specification. The same form covers async methods, generator methods (*ids() {}) and async generator methods; getters and setters (get label() {}) already existed in ES5 and share the grammar. A method definition differs from a function expression in three observable ways:

  • It has a home object, so super.method() works inside it. A function property cannot use super.
  • It is not a constructor: new obj.method() throws a TypeError, and it has no prototype property.
  • Its name is the property key, the same as a named function property would get.
const baseFormatter = {
format(order) {
return `#${order.id}`;
},
};
const formatter = {
__proto__: baseFormatter, // literal __proto__: sets the prototype
format(order) {
return `${super.format(order)} (${order.status})`; // super works in methods
},
async load(id) { return { id, status: 'shipped' }; },
*ids() { yield 'ord-1'; yield 'ord-2'; },
get label() { return 'OrdersPortal formatter'; },
};
console.log(formatter.format(await formatter.load('ord-9')));
console.log([...formatter.ids()]);
console.log(formatter.format.name, formatter.label);
// Methods are not constructors and have no prototype property.
console.log('prototype' in formatter.format);
try {
new formatter.format({});
} catch (error) {
console.log(error.constructor.name + ': ' + error.message);
}
// A traditional function property is still constructible.
const legacy = { make: function () {} };
console.log(typeof new legacy.make());
// Shorthand __proto__ is an ordinary own property, not the prototype setter.
const __proto__ = { tag: 'not a prototype' };
const odd = { __proto__ };
console.log(Object.hasOwn(odd, '__proto__'), Object.getPrototypeOf(odd) === Object.prototype);
// Shorthand copies the current value; it is not a live binding.
let status = 'pending';
const snapshot = { status };
status = 'paid';
console.log(snapshot.status);

Output:

#ord-9 (shipped)
[ 'ord-1', 'ord-2' ]
format OrdersPortal formatter
false
TypeError: formatter.format is not a constructor
object
true true
pending

Two rules there are easy to miss: only the colon form __proto__: value sets the prototype (shorthand { __proto__ } creates an own property), and shorthand copies the value when the literal is evaluated.

The name must be a valid identifier reference, so reserved words and quoted keys are syntax errors, and a name that is not in scope throws:

try {
const order = { orderId, total: 10 };
} catch (error) {
console.log(error.constructor.name + ': ' + error.message);
}
for (const src of ['({ default })', '({ class })', '({ "order-id" })']) {
try { new Function(src); console.log('ok', src); }
catch (error) { console.log(src, '->', error.constructor.name + ': ' + error.message); }
}

Output (V8’s messages; other engines word them differently):

ReferenceError: orderId is not defined
({ default }) -> SyntaxError: Unexpected token 'default'
({ class }) -> SyntaxError: Unexpected token 'class'
({ "order-id" }) -> SyntaxError: Unexpected string

OrdersPortal wraps its HTTP API in a client factory: a shorthand property passes the configuration through, the endpoints are shorthand async methods, and a getter exposes a counter kept private in the closure. The last line wraps variables in { } so the console prints their names.

// orders-client.mjs - a small OrdersPortal client built with shorthand syntax.
function createOrdersClient({ baseUrl, fetchImpl = fetch }) {
let requestCount = 0; // private state captured by the methods below
async function request(path) {
requestCount++;
const response = await fetchImpl(`${baseUrl}${path}`);
if (!response.ok) throw new Error(`GET ${path} failed with HTTP ${response.status}`);
return response.json();
}
return {
baseUrl, // shorthand property
async getOrder(id) {
return request(`/orders/${id}`);
},
async listOrders({ status = 'open', limit = 20 } = {}) {
const query = new URLSearchParams({ status, limit });
return request(`/orders?${query}`);
},
get requestCount() {
return requestCount;
},
};
}
// A fake fetch so the sample runs offline.
const fakeFetch = async (url) => ({
ok: true,
json: async () => ({ url }),
});
const client = createOrdersClient({ baseUrl: 'https://api.example.test', fetchImpl: fakeFetch });
const order = await client.getOrder('ord-1042');
const open = await client.listOrders({ limit: 5 });
const requestCount = client.requestCount;
console.log({ order, open, requestCount }); // shorthand doubles as labeled debug output

Output:

{
order: { url: 'https://api.example.test/orders/ord-1042' },
open: { url: 'https://api.example.test/orders?status=open&limit=5' },
requestCount: 2
}

The mirror image of shorthand is destructuring, as in the { baseUrl, fetchImpl = fetch } parameter: shorthand builds an object from variables, destructuring builds variables from an object.

  • Expecting an arrow function’s this. A shorthand method gets this from the call site, like any function. Passing a method that uses this, such as payload.describe, as a callback detaches it; bind it or wrap it in an arrow. (The OrdersPortal client above avoids this by using closures instead of this.) Conversely, an arrow-function property (count: () => this.items.length) does not see the object as this.
  • Calling a method with new. Code that used { Model: function () {} } as a constructor breaks if someone “modernizes” it to { Model() {} }. Use a class for anything constructed.
  • Assuming a live binding. { status } copies the value once. Use a getter (get status() { return status; }) if the object must reflect later changes.
  • Using { __proto__ } to set a prototype. Only __proto__: value does that. Prefer Object.create(proto) when intent matters.

Use shorthand properties whenever the property name matches an existing variable, and shorthand methods for object-literal APIs, especially when a method needs super.

Keep the long form when:

  • The names differ. { id: orderId } is clearer than renaming a variable just to use shorthand.
  • You need new. Use a class, or a function property in code that must stay constructible.
  • You need lexical this. An arrow-function property captures the surrounding this, which a method cannot do.
  • The key is not an identifier ('order-id') or is computed: use a quoted key or a computed property name.

According to MDN’s browser compatibility data, shorthand property names are supported in Chrome 47, Edge 12, Firefox 33, Safari 9 and Node.js 4.0.0; shorthand method names in Chrome 47, Edge 12, Firefox 34, Safari 9 and Node.js 4.0.0. Deno 1.0 and Bun 1.0 support both. Internet Explorer never supported either. Compilers targeting ES5 rewrite shorthand into key: key and key: function () {} (checked with @babel/preset-env 8.0 targeting IE 11 and TypeScript 5.9 tsc --target es5), so the downleveled method becomes constructible again.

1. What is the difference between { load() {} } and { load: function () {} }? Both create a function-valued property named load with dynamic this. The method form has a home object, so it can use super, and it is not a constructor: it has no prototype property and new obj.load() throws a TypeError.

2. What does { status } contain if status changes after the object is created? The old value. Shorthand evaluates the identifier once and stores its value; it is not a reference to the variable. Use a getter if you need the current value.

3. Why does { __proto__ } not set the prototype while { __proto__: proto } does? The specification only treats the colon form with the literal name __proto__ as the prototype setter. Shorthand and computed forms create an ordinary own property called __proto__.

4. Senior scenario: a team converts a legacy object-literal module to shorthand methods and some callers break. What do you check? First, any caller that uses new on a former function property: shorthand methods are not constructible, so those become classes or stay as function properties. Second, callbacks: arrow-function properties that relied on lexical this must not be converted to methods. Third, anything that inspected fn.prototype. Add tests for those three before any mechanical lint fix: ESLint’s object-shorthand rule accepts a "properties" option, so you can auto-fix properties first and convert methods by hand after review.

  • { x } is { x: x }, evaluated once; m() {} defines a method without function.
  • Shorthand methods can use super and cannot be called with new.
  • Only __proto__: value sets the prototype; { __proto__ } does not.
  • Keep the long form for different names, constructors and lexical this.