Object Destructuring

Object Destructuring Assignment

Destructuring unpacks properties into variables with a pattern that mirrors the object. key: target renames, = value is a default used when the property is undefined (not null), nested patterns reach into child objects, and ...rest collects the remaining properties. In prefs: { theme } only theme becomes a variable. A nested pattern throws a TypeError if the parent is missing, so write prefs: { theme } = {} when it is optional. In parameters, destructuring gives you named, optional arguments. Array patterns follow in Destructuring Assignment.

Renaming, defaults, nesting, rest and parameter destructuringJavaScriptLive
const user = { id: 42, name: "Ada", prefs: { theme: "dark" } };
const { name, role = "viewer", prefs: { theme }, email: mail = "n/a", ...rest } = user;
let id;
({ id } = user);                  // parentheses: a bare { would start a block
const connect = ({ host = "localhost", port = 8080 } = {}) => `${host}:${port}`;
console.log(name, role, theme, mail, rest, id, connect({ port: 3000 }));