freecoding.school100% FREE · NO SIGNUP
Closure CavesISSUE #16 of 61

computed property names

LambdaVSThe Mutator
Lambda saysComputed property names let you use a variable or expression as an object key.

Wrap a key in brackets to compute it: { [keyVar]: value } or { ['user_' + id]: data }. This builds objects with dynamic keys in one literal instead of creating the object then assigning. Common for keying by id, building lookup maps, and reducers.

Power-ups you unlock

The Mutator attacks — common mistakes

Boss battleBuild an object whose key comes from a variable using computed property syntax.

Example code

<!doctype html><html><head><meta charset="utf-8"></head>
<body style="background:#06040d;color:#e6e0ff;font-family:monospace;padding:20px"><pre id="o"></pre>
<script>const field='email'; const rec={ [field]:'a@b.com', ['id_'+7]:7 };
document.getElementById('o').textContent=JSON.stringify(rec);</script></body></html>
▶ Open the interactive comic issue
‹ Spread On Objects · MergingGetters · Setters · Accessors ›