JavaScript Object Literal Syntax: Shorthand Properties, Computed Keys, Methods and Spread
The modern object literal: shorthand properties, computed property names, symbol keys, shorthand methods (and how they differ from function properties and arrow functions), super in literals, __proto__ in literals, spread, duplicate keys and evaluation order.
kvi5hnuCode Sprout team member6 min readOn this page
Object literals started out as simple name: value lists. Since ES2015 they've gained a set of features that make them shorter and much more expressive, and modern JavaScript code uses them everywhere: React components, configuration objects, API payloads, module exports.

Shorthand properties
When a property should have the same name as a variable holding its value, write the name once:
const name = "Ana";
const age = 31;
const user = { name, age }; // same as { name: name, age: age }
console.log(user);
function makeUser(name, role = "viewer") {
return { name, role, active: true }; // mix shorthand and normal properties
}
console.log(makeUser("Bo"));
{ name: 'Ana', age: 31 }
{ name: 'Bo', role: 'viewer', active: true }
Shorthand is the mirror image of object destructuring (article 28): const { name, age } = user takes properties out into variables; { name, age } puts variables back into properties. You'll see the pair constantly, for example when returning several values from a function: return { total, count };, then const { total, count } = summarize(data);.
Computed property names
When the property name is in a variable or must be calculated, put an expression in square brackets inside the literal:
const field = "email";
const form = {
[field]: "ana@example.com",
[`${field}Verified`]: false,
[2 + 3]: "five",
};
console.log(form);
{ '5': 'five', email: 'ana@example.com', emailVerified: false }
The expression is evaluated, converted to a string (or kept as a symbol), and used as the key, just like bracket access (article 47). Before ES2015, you had to create the object first and then assign obj[field] = value in a separate step.
A common use is updating one field of form state whose name comes from the input element:
function handleChange(state, event) {
return { ...state, [event.target.name]: event.target.value };
}
Computed keys are evaluated in order, left to right, along with the values:
let i = 0;
const sequence = { [i++]: i, [i++]: i };
console.log(sequence);
{ '0': 1, '1': 2 }
Symbol keys
Computed syntax is the only way to use a symbol as a key inside a literal (article 19):
const internalId = Symbol("internalId");
const record = { [internalId]: 7, title: "Report" };
console.log(record[internalId], Object.keys(record), JSON.stringify(record));
7 [ 'title' ] {"title":"Report"}
Symbol keys never clash with string keys or with other code's symbols, and they're skipped by Object.keys, for...in and JSON. That makes them good for attaching metadata to objects you don't own. They aren't private, though: Object.getOwnPropertySymbols finds them. For real privacy, use class private fields (part 9).
The most important symbol keys are the well-known symbols, which plug objects into language features: [Symbol.iterator] makes an object work with for...of and spread (part 12), [Symbol.toPrimitive] controls conversions (article 24), [Symbol.toStringTag] sets the type tag (article 51).
Shorthand methods
A method is a function stored in a property. Literals have a dedicated syntax for it:
const helper = Symbol("helper");
const calculator = {
double(n) { return n * 2; }, // same idea as double: function (n) {...}
"add one"(n) { return n + 1; }, // any key form works
[helper](n) { return n - 1; }, // including computed and symbol keys
async fetchRate() { return 1.1; }, // async methods
*range() { yield 1; yield 2; }, // generator methods
};
console.log(calculator.double(4), calculator["add one"](1), calculator[helper](10));
console.log(calculator.fetchRate() instanceof Promise, [...calculator.range()]);
console.log(calculator.double.name);
8 2 9
true [ 1, 2 ]
double
Shorthand methods aren't exactly the same as name: function () {}:
- They can't be called with
new: they aren't constructors and have noprototypeproperty. That's what you want for methods. - They can use
superto reach the prototype's version of a method (below). - Both kinds get a
namefrom their key, which helps in stack traces.
const shorthand = { make() { return {}; } };
const longhand = { make: function () { return {}; } };
try {
new shorthand.make();
} catch (err) {
console.log("shorthand:", err.name);
}
console.log("longhand:", typeof new longhand.make());
shorthand: TypeError
longhand: object
Don't use arrow functions as methods
Arrow functions don't have their own this: they use the this of the code around them, not the object they're called on (part 8). As object methods that read this, they're almost always a bug:
(function () {
"use strict";
const counter = {
count: 5,
regular() { return this.count; },
arrow: () => this, // "this" of the enclosing function, not counter
};
console.log(counter.regular(), counter.arrow());
})();
5 undefined
Arrow functions are great inside methods, for callbacks that should keep the method's this: items.map((item) => item.price * this.taxRate).
super in object literals
Inside a shorthand method, super.method() calls the method from the object's prototype, so you can extend inherited behavior instead of replacing it:
const base = { greet() { return "hello"; } };
const polite = {
__proto__: base,
greet() { return `${super.greet()}, nice to meet you`; },
};
console.log(polite.greet());
hello, nice to meet you
super only works in shorthand methods (and in classes, part 9); in a function expression it's a SyntaxError.
proto in a literal
The example above used another literal feature: a property written as __proto__: value (not computed, not shorthand) sets the new object's prototype instead of creating a property. It's standardized and is the literal equivalent of Object.create:
const animal = { kind: "animal" };
const cat = { __proto__: animal, sound: "meow" };
console.log(cat.kind, Object.keys(cat));
const dict = { __proto__: null }; // a null-prototype object (article 46)
console.log(Object.getPrototypeOf(dict));
console.log(Object.keys({ ["__proto__"]: 1 })); // computed: an ordinary property
animal [ 'sound' ]
null
[ '__proto__' ]
Only the literal form is recommended. The obj.__proto__ accessor on existing objects is a legacy feature; use Object.getPrototypeOf and Object.setPrototypeOf (part 14).
Spread in literals
{ ...source } copies an object's own enumerable properties into the new literal at that position (article 49). Combined with the other features, it gives concise "copy and change" expressions:
const position = { x: 0, y: 0 };
const moved = { ...position, y: 5 };
const tagged = { ...moved, ["label"]: "start", toString() { return `(${this.x}, ${this.y})`; } };
console.log(moved, String(tagged));
{ x: 0, y: 5 } (0, 5)
Getters and setters
Literals can also define accessor properties with get name() {} and set name(value) {}. They're important enough to get their own article: the next one.
Duplicate keys and trailing commas
A literal may repeat a key; the last one wins (strict mode allowed duplicates as of ES2015, because computed keys made it impossible to detect them in general). It's almost always a mistake, and ESLint's no-dupe-keys catches the literal cases:
const settings = { theme: "light", size: 12, theme: "dark" };
console.log(settings);
{ theme: 'dark', size: 12 }
Note that the key keeps its original position but takes the later value. Trailing commas after the last property are allowed.
Returning an object literal from an arrow function
An arrow function whose body starts with { is parsed as a block, not an object. Wrap the literal in parentheses:
const wrong = (n) => { value: n }; // a block with a label "value"
const right = (n) => ({ value: n });
console.log(wrong(1), right(1));
undefined { value: 1 }
Common questions
Is { name } the same as { name: name }?
Yes, exactly. The shorthand only works with plain identifiers, so { user.name } is a SyntaxError; write { name: user.name }.
Can computed keys be anything?
Any expression. Objects used as keys are converted to strings (usually "[object Object]"), so in practice they're strings, numbers or symbols.
When should I use a method vs a function property?
Use method shorthand for functions that belong to the object and use this. Use a property holding an arrow function for callbacks or handlers that must not depend on how they're called, like { onClick: () => setOpen(true) }.
Do these features work in JSON?
No. JSON (article 50) only allows double-quoted keys with literal values: no shorthand, computed keys, methods, spread or comments.
Summary
{ name, age }creates properties from variables of the same name.{ [expression]: value }computes the key at run time; it's the only way to write symbol keys in a literal.name() {}defines a method; methods can be async or generators, can usesuper, and can't be called withnew.- Avoid arrow functions as methods that read
this. __proto__: protoin a literal sets the prototype; a computed["__proto__"]creates a normal property....sourcecopies own enumerable properties; later properties override earlier ones, and duplicate keys keep the last value.- Wrap object literals returned from arrow functions in parentheses.
Practice Questions
What does this print?
const x = 1, y = 2;
const o = { x, y, [x + y]: "sum" };
console.log(o);
Answer
{ '3': 'sum', x: 1, y: 2 }. The computed key is "3", an integer-like key, so it's listed first.
Rewrite this code as one literal.
const o = {};
o[type + "Count"] = 0;
o.reset = function () {
this[type + "Count"] = 0;
};
Answer
const o = { [type + "Count"]: 0, reset() { this[type + "Count"] = 0; } };
Why does this code not work?
const api = { base: "/v1", url: () => this.base + "/users" };
Answer
url is an arrow function, so this is the surrounding code's this, not api. Use a method: url() { return this.base + "/users"; }.
What does this code return, and how do you fix it?
const make = (id) => {
id
};
Answer
It returns undefined: the braces are a function body containing the expression statement id. Write (id) => ({ id }).
Previous: JavaScript Object Methods: toString, toLocaleString, valueOf and toJSON
Next: JavaScript Getters and Setters: Accessor Properties, Validation and Computed Values

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.