CKTIS / JavaScript
Object shorthand syntax
Create properties from existing variables and define methods without `function`. Distinguish property shorthand from computed keys and destructuring.
Version: ECMAScript 2024 and the current web platform; runtime support varies
Syntax
const obj = { count, total: count, [key]: value, double() { return this.count * 2; } };Object shorthand syntax includes two forms in object literals. The property form { count } creates an own data property with the key "count", just like { count: count }. It reads the current value of count: reassigning the variable later does not update the property. An object value is not cloned. Reading an undeclared variable throws a ReferenceError.
Use { total: count } to store the value under a different name, or { [key]: value } to compute the key from an expression. Watch out for __proto__: { __proto__ } creates an own property, but { __proto__: value } sets the new object's prototype if value is an object or null, and otherwise does nothing.
The form double() { return this.count * 2; } defines a method without function. In obj.double(), this is obj. The syntax does not permanently bind this to obj, and an arrow function instead takes this from its surrounding scope. Unlike an ordinary function expression, a concise method isn't a constructor: new obj.double() throws a TypeError.
In const { count } = obj, the braces form a destructuring pattern: you read a property instead of creating one. Both shorthand forms were introduced in ECMAScript 2015 and are part of ECMAScript 2024; check support in your target runtime. Neither form is valid JSON.
Examples
{
let count = 2;
const key = "label";
const obj = {
count,
[key]: "items",
double() {
return this.count * 2;
},
};
count = 7;
console.log(obj.count);
console.log(obj.label);
console.log(obj.double());
}Result
2 items 4
After `count = 7`, `obj.count` is still `2`. The computed key is `label`, and `obj.double()` returns `4` because it uses the object's property.
Related lessons
- JavaScript · Lesson 32 · Advanced · Version: 4