The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.
The destructuring assignment uses on the left-hand side of the assignment to define what values to unpack from the sourced variable.
const settings = {
notification: {
follow: true,
alerts: true,
unfollow: false,
},
color: {
theme:"dark"
},
};
const { notification: {follow},
color,} = settings;
console.log(follow) // true
console.log(color) // {theme: 'dark'}
const days = ["Mon", "Tue", "Wed"];
const [mon, tue, wed, thu="Thu"] = days;
console.log(mon, tue, wed, thu) // Mon Tue Wed Thu
const settings = {
color: { chosen_color: "dark"},
};
const{
color: {chosen_color: chosenColor = "light"},
} = settings;
console.log(chosenColor); // dark
function saveSettings(settings) {
console.log(settings); // {followAlert: true, mrkAlert: true}
}
saveSettings({
followAlert: true,
mrkAlert: true,
})
function saveSettings({Alert, popup, color = false}) {
console.log(color); // false
}
saveSettings({
Alert: true,
popup: true,
});
// Swapping
let mon = "Sat";
let sat = "Mon";
[sat, mon] = [mon, sat];
console.log(mon, sat); // Mon Sat
// Skipping
const days = ["mon", "tue", "wed", "thu", "fri"];
const [, , , thu, fri] = days;
console.log(thu, fri); // thu fri
출처
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment