0 day streak
javascript / intermediate
Snippet

Object Destructuring with Aliasing and Defaults

Destructuring can extract nested properties and assign them to new variable names (aliasing) in a single step. You can also provide default values that are used if a property is missing or undefined.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
const userResponse = { id: 42, meta: { lastLogin: '2023-01-01' } };
const {
id: userId,
meta: { lastLogin: loginDate },
role = 'guest'
} = userResponse;
console.log(userId, loginDate, role);
Breakdown
1
id: userId
Extracts the 'id' property but assigns its value to a new constant named 'userId'.
2
role = 'guest'
Declares a 'role' variable with a fallback value of 'guest' if the property doesn't exist in userResponse.