JavaScript Object Destructuring: Rename and Default Fields
Quick answer
Object destructuring reads named properties into bindings. Unlike array patterns, it selects by key, not position.
How it works
Use const {price: cost, quantity = 1} = item. The colon maps the property key to a new binding name. An absent property reads as undefined; inherited properties can also be read. A nested pattern needs a non-nullish intermediate value.
const item = {price: 12};const {price: cost, quantity = 2} = item;console.log(cost * quantity);Expected output in Node.js:
24The alias is 12 and the missing quantity defaults to 2.
const {size = 3} = {size: 0};console.log(size);Expected output in Node.js:
0Zero is not undefined.
Common mistakes
The alias is the local name, not a rename of the original object. Destructuring null or undefined fails.
Practice
Unpack a product name into label and use a default stock count.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript Object Destructuring: Rename and Default Fields — Knowledge Check
Apply the taught concept and predict the output.
In const {name: label} = item, which local binding is declared?
Which source cannot be destructured using an object binding pattern?
Does an object binding pattern only read own properties?
What is the exact console output in JavaScript Object Destructuring: Rename and Default Fields example 1?
const item = {price: 12};const {price: cost, quantity = 2} = item;console.log(cost * quantity);What is the exact console output in JavaScript Object Destructuring: Rename and Default Fields example 2?
const {size = 3} = {size: 0};console.log(size);