capypad
0 day streak
javascript / intermediate
Snippet

Object Destructuring with Aliasing and Defaults

Destructuring allows extracting object properties into variables with custom names (aliasing) and default values if the property is missing.

snippet.js
javascript
1
2
3
const config = { id: 101 };
const { id: userId, theme = 'dark' } = config;
console.log(userId, theme);
Breakdown
1
id: userId
Extracts the 'id' property and renames it to 'userId'.
2
theme = 'dark'
Assigns 'dark' if the 'theme' property does not exist in config.