Sub topic 4
Shorthand Properties and Computed Keys
Earlier chapters showed that an object literal is a list of key: value pairs and that keys are strings or symbols. This chapter covers two pieces of literal syntax that make objects shorter to write and let you build keys at runtime. Shorthand properties let you leave out the key when it matches a variable name. Computed keys let you put any expression in square brackets and use its result as the key.
This chapter assumes you know let and const, function and arrow function syntax, template literals, and how to run code in Node.js or a browser console. It also assumes you have read the earlier chapters on dot and bracket access and on property keys.
Shorthand Property Names
Code often creates a variable and then stores it in an object under the same name. Writing name: name repeats the name. Shorthand syntax lets you write the name once:
const name = "Ada";
const born = 1815;
const longhand = { name: name, born: born };
const shorthand = { name, born };
console.log(longhand); // { name: 'Ada', born: 1815 }
console.log(shorthand); // { name: 'Ada', born: 1815 }The two objects are identical. In { name }, the identifier name serves two purposes. It is the property key, as the string "name", and it is a variable lookup that supplies the value. You can mix shorthand and longhand entries in one literal.
Shorthand is most useful when a function returns several values together:
function stats(numbers) {
const min = Math.min(...numbers);
const max = Math.max(...numbers);
const mean = numbers.reduce((a, b) => a + b, 0) / numbers.length;
return { min, max, mean };
}
console.log(stats([2, 4, 9])); // { min: 2, max: 9, mean: 5 }Common errors with shorthand
The value comes from a variable lookup, so the variable has to exist. A misspelled name throws an error. It does not quietly create an undefined property:
const title = "Notes";
try {
const doc = { title, autor: "Lin" }; // fine: longhand
const broken = { titel }; // typo in shorthand
} catch (err) {
console.log(err.name); // "ReferenceError"
}The second common error appears in arrow functions. When an arrow function's body begins with {, JavaScript reads that brace as the start of a function body, not as an object literal:
const wrong = (x, y) => { x, y }; // block body; `x, y` is a comma expression
const right = (x, y) => ({ x, y }); // parentheses force an object literal
console.log(wrong(1, 2)); // undefined
console.log(right(1, 2)); // { x: 1, y: 2 }The wrong function runs without a syntax error. It evaluates x, y, throws the result away, and returns undefined. Wrap the object in parentheses whenever an arrow function returns an object literal.
Shorthand Method Syntax
Literals also have a short form for function-valued properties. Write area() { ... } instead of area: function () { ... }:
const rect = {
width: 3,
height: 4,
area() {
return this.width * this.height;
}
};
console.log(rect.area()); // 12Shorthand methods behave a little differently from function expressions. A shorthand method cannot be used as a constructor, so new rect.area() throws a TypeError. Shorthand methods can use super to reach the object's prototype, which is covered in the prototype chapter. How this is bound is covered in the chapter on methods.
Computed Keys
Sometimes the key is unknown until the program runs. It might come from a function argument, a loop variable, or a symbol. A computed key puts an expression inside square brackets in key position:
const key = "color";
const car = { make: "Toyota", year: 2020, [key]: "red", "top speed": 180 };
console.log(car.make); // "Toyota"
console.log(car["top speed"]); // 180
console.log(car.color); // "red"
console.log(car.model); // undefinedBefore ES2015, the only way to get this result was to create the object first and then assign car[key] = "red" in a second statement. With computed keys, the whole object is built in one expression. This matters when you return an object from a function or pass one as an argument.
Any expression works inside the brackets. Examples include arithmetic, function calls, and template literals:
const prefix = "user";
const id = 42;
const record = {
[`${prefix}_${id}`]: "Lin",
[id + 1]: "next",
[prefix.toUpperCase()]: true
};
console.log(record); // { '43': 'next', user_42: 'Lin', USER: true }Key 43 is listed first because it is an integer-like key. The ordering rules are explained in the chapter on listing properties.
How a computed key becomes a property key
A property key can only be a string or a symbol. JavaScript evaluates the bracketed expression and converts the result. If the result is a symbol, it is used as is. Any other value is converted to a string.
That string conversion explains several results that look surprising at first:
const sym = Symbol("id");
const objKey = { a: 1 };
const weird = {
[sym]: "symbol key",
[objKey]: "object key",
[["x", "y"]]: "array key",
[null]: "null key",
[1.50]: "number key"
};
console.log(Object.keys(weird));
// [ '[object Object]', 'x,y', 'null', '1.5' ]
console.log(weird[sym]); // "symbol key"
console.log(weird["[object Object]"]); // "object key"Using a plain object as a key is almost always a bug. Every plain object converts to the same string, "[object Object]", so two different objects used as keys overwrite each other. If you need objects as keys, use a Map.
The symbol key does not appear in Object.keys, because that method returns only string keys. You can still read it with weird[sym].
Evaluation order
Entries in a literal are evaluated left to right. Within each entry, the key expression runs before the value expression. The order only matters when expressions have side effects, but when they do, it is predictable:
const log = [];
const k = (name) => { log.push(`key ${name}`); return name; };
const v = (val) => { log.push(`value ${val}`); return val; };
const obj = { [k("a")]: v(1), [k("b")]: v(2) };
console.log(log); // [ 'key a', 'value 1', 'key b', 'value 2' ]
console.log(obj); // { a: 1, b: 2 }Duplicate keys
A literal can produce the same key more than once, either by repeating it or because a computed expression lands on an existing key. This is not an error. The last definition wins, and the property stays in the position where its key first appeared:
const field = "a";
const dup = { a: 1, b: 2, [field]: 3 };
console.log(dup); // { a: 3, b: 2 }Computed method names
Computed keys work with method shorthand too. You can generate method names, or use a well-known symbol such as Symbol.iterator as a key:
const fields = ["name", "email"];
const api = {
[`get${fields[0][0].toUpperCase()}${fields[0].slice(1)}`]() {
return "Ada";
},
*[Symbol.iterator]() {
yield* fields;
}
};
console.log(api.getName()); // "Ada"
console.log([...api]); // [ 'name', 'email' ]A Common Pattern: Updating One Field
Computed keys show up often in code that updates one field of an object by name, such as form handlers or state reducers:
function setField(state, field, value) {
return { ...state, [field]: value };
}
const form = { name: "", email: "" };
const next = setField(form, "email", "[email protected]");
console.log(next); // { name: '', email: '[email protected]' }
console.log(form); // { name: '', email: '' }The ...state spread copies the existing properties, and [field]: value overwrites the one being changed. It works because of the last-definition-wins rule above. The chapter on references and copying explains the copy that spread makes.
Choosing the Right Form
| You want | Write | Key produced |
|---|---|---|
| A fixed, identifier-like key | `{ size: 10 }` | `"size"` |
| A fixed key with spaces or dashes | `{ "max-age": 60 }` | `"max-age"` |
| A key named after a variable, with that variable's value | `{ size }` | `"size"` |
| A key taken from a variable's value | `{ [size]: 10 }` | `String(size)` |
| A symbol key | `{ [sym]: 10 }` | the symbol itself |
The most frequent mix-up is between { key: value } and { [key]: value }. Without brackets, key is the literal string "key". With brackets, it is the variable key and whatever value it holds. Shorthand cannot be combined with brackets either. { [key] } is a syntax error, because a computed entry must have an explicit value.
Exercises
Exercise
What does this code print, and why? const a = "x"; const b = "y"; const o = { a, [b]: a, b: 1 }; console.log(o);
Show answer
It prints { a: 'x', y: 'x', b: 1 }. The shorthand a creates key "a" with value "x". The computed [b] evaluates the variable b to "y", so it creates key "y" with value "x". The plain b: 1 uses the literal string "b" as its key and ignores the variable.
Exercise
A cache is written as const cache = {}; function remember(req, res) { Object.assign(cache, { [req]: res }); }, where each req is a different plain object. After two calls, the cache holds only one entry. Explain why and suggest a fix.
Show answer
A computed key that is not a symbol is converted to a string, and every plain object converts to "[object Object]". Both calls write to the same key, and the second overwrites the first. Use a Map, for example const cache = new Map(); cache.set(req, res);, because a Map uses the object itself as its key.
Exercise
Rewrite const toPair = (k, v) => { const o = {}; o[k] = v; return o; }; as a single-expression arrow function, and explain the parentheses you need.
Show answer
const toPair = (k, v) => ({ [k]: v });. The computed key [k] uses the value of k. The parentheses make JavaScript parse the braces as an object literal. Without them, the braces would be read as a function body.