Sub topic 4
Shorthand Properties and Computed Keys
This chapter assumes you can write object literals, read properties with dot and bracket notation, and know that property keys are strings or symbols. It covers two literal features that cut repetitive code: shorthand properties, which build properties from variables, and computed keys, which let a property name come from an expression.
Shorthand Properties
Often you build an object from variables that already have the names you want for the properties. Without shorthand, you write each name twice:
const name = "Lin";
const age = 34;
const verbose = { name: name, age: age };
const short = { name, age };
console.log(short); // { name: "Lin", age: 34 }Writing { name } is the same as writing { name: name }. The property key is the identifier as a string, and the value is whatever that variable holds when the literal is evaluated. You can mix shorthand and regular properties in one literal:
function makePoint(x, y) {
return { x, y, label: `(${x}, ${y})` };
}
console.log(makePoint(3, 4)); // { x: 3, y: 4, label: "(3, 4)" }Shorthand works only with plain identifiers. { user.name } is a syntax error. If no variable with that name is in scope, you get a ReferenceError when the literal runs.
Computed Keys
Square brackets around a key in a literal mark it as a computed key. JavaScript evaluates the expression inside the brackets and uses the result as the property name.
const field = "email";
const i = 2;
const record = {
[field]: "[email protected]",
[`item${i}`]: "book",
[1 + 1]: "two"
};
console.log(record.email); // "[email protected]"
console.log(record.item2); // "book"
console.log(record["2"]); // "two"Without the brackets, { field: ... } would create a property literally named "field". That is the most common mistake with dynamic keys.
Computed keys are useful when the property name is only known at runtime:
function makeEntry(key, value) {
return { [key]: value, updatedAt: Date.now() };
}
console.log(makeEntry("theme", "dark")); // { theme: "dark", updatedAt: ... }How the Key Is Converted
If the expression produces a symbol, the symbol is used as the key. Any other value is converted to a string.
Computed keys are the only way to put a symbol key directly in a literal:
const id = Symbol("id");
const item = { [id]: 123, name: "lamp" };
console.log(item[id]); // 123String conversion causes a common bug when you use objects as keys. Every plain object converts to the same string:
const a = { id: 1 };
const b = { id: 2 };
const lookup = { [a]: "first", [b]: "second" };
console.log(Object.keys(lookup)); // ["[object Object]"]
console.log(lookup[a]); // "second"Both keys became "[object Object]", so the second value overwrote the first. To key by object identity, use a Map.
Common Errors
| Symptom | Cause | Fix |
|---|---|---|
| Property named `"field"` instead of its value | Brackets missing around a dynamic key | Write `[field]: value` |
| `ReferenceError` in a literal | Shorthand name has no matching variable | Declare the variable or use `key: value` |
| Values overwriting each other | Object keys all become `"[object Object]"` | Use a `Map` or a string ID as the key |
| Unexpected value for a key | Duplicate keys in one literal; the last one wins | Remove or rename duplicates |
Exercise
Given const prop = "size"; const size = 10;, what does { prop, [prop]: size * 2, size } evaluate to, and why?
Show answer
{ prop: "size", size: 10 }. The shorthand prop creates the key "prop" with the value "size". The computed [prop] creates the key "size" with the value 20. The later shorthand size then overwrites that key with 10, because when a literal has duplicate keys, the last one wins.
Exercise
Write a function pick(key, source) that returns a new object with only that one property from source, using a computed key.
Show answer
function pick(key, source) { return { [key]: source[key] }; } For example, pick("a", { a: 1, b: 2 }) returns { a: 1 }.