Question presented to candidate: "You need to build an object literal where one of the keys comes from a variable, not a hardcoded name — say, mapping each item in an array to a dynamic key based on its own name. How do computed property names solve this directly inside an object literal, without a separate assignment step afterward?"
What a strong answer should cover:
- 📌 Interview term: computed property names — wrapping an expression in square brackets inside an object literal's key position (
{ [expr]: value }) evaluates that expression at object-creation time and uses the real result as the actual key. - 📌 Verified, not assumed: a real object literal genuinely evaluated a plain variable, a template literal, AND a numeric expression (
1 + 1) as computed keys — the numeric one was genuinely coerced to the string key"2", confirmed directly, since real object keys are always strings (or Symbols). - A precise answer names that this syntax works identically for computed method names (
{ [methodName]() {...} }) and for Symbol-valued computed keys, not just plain data properties — verified directly: a real Symbol-keyed computed property worked, and was genuinely excluded fromObject.keys(), only visible viaObject.getOwnPropertySymbols(). - A precise answer names the real, direct, practical payoff for the prompt's scenario: building an object dynamically from an array via
.reduce()with a computed key genuinely works in a single literal expression, verified directly — no separateobj[key] = valueassignment statement needed afterward. - The precise, honest scope: computed property names are an ES2015 (ES6) addition — before that, the identical dynamic-key result required the separate, two-step
obj[keyVar] = valuebracket-assignment form, verified directly to produce an identical real result.
Clarifying questions expected:
- "Does the dynamic key genuinely need to be computed fresh from a variable/expression at object-creation time, or would a plain, separate bracket assignment afterward work just as well for this specific case?" — computed property names are a genuine convenience, not a new capability bracket assignment lacked.
- "Could any of the computed key expressions genuinely produce the same key twice within the same literal?" — the later one would genuinely win, same as any other duplicate-key object literal behavior.
Code / implementation expected: Yes — a real object literal using computed property names for a variable, a template literal, a numeric expression, a method name, and a Symbol, with the real resulting object inspected directly, is the concrete, convincing proof of exactly how and where this syntax applies.