Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Object destructuring, property shorthand, and computed access

Distinguish binding values from an object, defining properties with shorthand, and accessing properties through keys evaluated at runtime.

Version: ECMAScript 2024 and the current web platform; runtime support varies

Syntax

// Define properties: shorthand and computed key
const obj = { name, [key]: value };

// Bind values: same name, rename, default, computed key, and rest
const { name: alias, active, level = 1, [key]: selected, ...rest } = obj;

// Assign to an existing writable variable
let current;
({ name: current } = obj);

// Read properties: fixed key and computed key
obj.name;
obj["name"];
obj[key];

Object destructuring/shorthand/computed access covers three distinct uses of object syntax. In const { name } = obj, destructuring reads name and declares a variable with the same name. In const { name: alias } = obj, the key is on the left of the colon and the new variable is on the right. For a standalone assignment to an existing writable variable, use ({ name: alias } = obj);: the parentheses keep { from being parsed as the start of a block.

In the object literal const obj = { name }, the shorthand name means name: name: the existing variable supplies the value of a new property. In a literal, [key]: value defines a property; in a destructuring pattern, [key]: alias reads a property into alias. In both cases the bracketed expression determines the key. If the expression evaluates to an object, JavaScript first converts it to a primitive. If the primitive is a Symbol, it is used unchanged as the property key; otherwise, it is converted to a string. The conversion can throw.

obj.name and obj["name"] read the same fixed key; obj[key] evaluates key to choose the key. Both ordinary reads and explicit property reads in destructuring can find inherited properties. Check keys from untrusted input against an allowlist before using them.

A default such as level = 1 is evaluated only when the read yields undefined, not null. Destructuring null or undefined itself throws a TypeError. Put ...rest last, with no trailing comma: it shallow-copies the remaining own enumerable properties into a new object, including symbol-keyed properties. The syntax is specified in ECMAScript 2024; check support in your target runtime.

Examples

{
  const name = "Ada";
  const key = "total-score";
  const obj = { name, [key]: 7, active: true, note: null, tag: "demo" };
  const { name: alias, [key]: score, active, level = 1, note = "none", ...rest } = obj;
  console.log(`${alias} | ${score} | ${obj[key]} | ${active} | ${level} | ${note} | ${rest.tag}`);
}

Result

Ada | 7 | 7 | true | 1 | null | demo

`[key]: score` and `obj[key]` both read `7`; the missing `level` takes the default `1`, `note` stays `null`, and `tag` goes into `rest`.

Related lessons

  • JavaScript · Lesson 43 · Advanced · Version: 4

Sources