JavaScript Destructuring Defaults and Renaming
A default is a fallback value used when a property is missing. Renaming gives a pulled value a different variable name.
A missing value takes the default
The object has no city property. The default fills in for the missing value.
const user = { name: "Ana" };
const { name, city = "Unknown" } = user;
console.log(name);
console.log(city);A present value ignores the default
The object holds a city, so the default never runs. The real value wins.
const user = { name: "Ana", city: "Seattle" };
const { city = "Unknown" } = user;
console.log(city);Rename while pulling
The colon renames the value as it is pulled out. The property name stays on the left, and the new variable name goes on the right.
const user = { name: "Ana", age: 28 };
const { name: fullName, age: years } = user;
console.log(fullName);
console.log(years);Default with a rename
A rename and a default can share one entry. The default fills in only when the property is missing.
const settings = { theme: "dark" };
const { theme: mode = "light", size = 14 } = settings;
console.log(mode);
console.log(size);Example
const product = { title: "Lamp", price: 25 };
const { title: item, price, stock = 0 } = product;
console.log(item);
console.log(price);
console.log(stock);Key points
- Default: a value used when the property is missing or holds undefined
- Write a default after the name with an equals sign, like city = "Unknown".
- A default runs only when the value is missing.
- Rename: give a pulled value a new name with a colon, like name: fullName
- Renaming keeps the property name on the left and the new variable on the right.
In this example, the title is renamed to item while it is pulled out. The price has no default and is present, so it stays 25. The stock is missing, so the default 0 fills in.
Note
A default does not replace null. Only a missing value or undefined takes the default.
Try it Yourself
Edit the code, then press Run.
Runs in your browser — the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
What is city after const { city = "Paris" } = {}?