Shorthand, Computed Keys, and Tricks
JavaScript Object Properties
Modern shortcuts for building objects — property shorthand, computed keys, spread, and method shorthand.
What you'll learn
- Use property value shorthand
- Compute keys at construction time
- Build objects with spread
A handful of small syntactic features make building objects in modern JavaScript pleasant.
Property Value Shorthand
When the key and the variable name match, you can write the variable once.
const name = "Ada";
const age = 36;
// Old:
const longHand = { name: name, age: age };
// New:
const shortHand = { name, age };
console.log(shortHand); // { name: 'Ada', age: 36 } This is everywhere in modern JS — making objects from local variables, returning structured data, etc.
Computed Property Names
Wrap an expression in [ ] inside the literal to compute a key.
const fieldName = "email";
const i = 3;
const obj = {
[fieldName]: "a@b.c",
[`field_${i}`]: true,
};
console.log(obj);
// { email: 'a@b.c', field_3: true } Useful when keys come from a variable, a function argument, or a template string.
Method Shorthand
When a property’s value is a function, you can drop the function
keyword and the : — write it like a method.
// Old:
const obj1 = {
greet: function (name) {
return `Hi, ${name}`;
},
};
// New:
const obj2 = {
greet(name) {
return `Hi, ${name}`;
},
};
console.log(obj2.greet("Ada")); // "Hi, Ada" Spread to Build New Objects
...obj inside another object literal copies its properties.
const defaults = { theme: "light", fontSize: 14 };
const overrides = { fontSize: 16, language: "en" };
const settings = { ...defaults, ...overrides };
console.log(settings);
// { theme: 'light', fontSize: 16, language: 'en' } Later spreads override earlier ones — this is the standard immutable update pattern. Combined with shorthand, you can patch one field elegantly:
const user = { name: "Ada", age: 36 };
const olderUser = { ...user, age: 37 };
console.log(user); // { name: 'Ada', age: 36 } (unchanged)
console.log(olderUser); // { name: 'Ada', age: 37 } This is the workhorse pattern in React, Redux, and most modern state management.
Rest in Destructuring (Removing a Property)
Combined with destructuring, rest gives you a quick way to drop a property:
const user = { name: "Ada", age: 36, secret: "shhh" };
const { secret, ...publicUser } = user;
console.log(publicUser); // { name: 'Ada', age: 36 } secret is “destructured out”, and publicUser is everything else.
Property Order
Strings keys preserve insertion order. Integer-looking keys come first, in numeric order. This is rarely something you’ll think about — most code works regardless.
Up Next
Methods on objects, and the Object.* helpers for iterating their
properties.