Originally posted at bjørn.dev
TLDR; I was wondering whether it would be possible to use Destructuring Assignment to assign a value directly to a property of an Object. Somehow I was not able to find any info about this online, not even on the MDN pages. Turns out it is possible, see below.
I’m sure that by now we all know about destructuring assignment in JavaScript. The straight forward destructuring assignment of an Array looks like this:
// suppose we have the array:
const x = [2, 3, 4, 5, 6];
// now we can assign values like this:
const [a] = x; // a === 2
const [,b] = x; // b === 3
const [,,c, ...rest]; // c === 4 && rest === [5, 6]
With Objects it’s also possible to use destructuring assignment:
// suppose we have the object
const y = {k: 42, l:96, m: 15, n: 16};
// assignment can be done like this
let {k} = y; // k === 42
let {l: d} = y; // d === 96
let {k, l: d, ...rest} = y; // k === 42 && d === 96 && rest === {m: 15, n: 16}
It’s even possible to use destructuring with function parameters:
// destructuring function parameters
function q({a, b}){
console.log(a, b);
}
q({a: 3, b: 5}); // logs: 3 5
// destructuring with reassignment
function r({a: x, b: y}){
console.log(x, y);
}
r({a: 33, b: 55}); // logs: 33 55
// with default values
function s({a = 3, b = 5, c = 7} = {}){
console.log(a, b, c);
}
s(); // logs: 3 5 7
s({b: 42}); // logs: 3 42 7
// with default values, nested objects and reassignment
function t({a: x = 3, b: y = 5, some: {value: z = 'empty'}} = {}){
console.log(x, y, z);
}
t({a: 6, some: {otherValue: 7}}); // logs: 6 5 "empty"
There are plenty more variants, like swapping values and using defaults. Most of them can be found in articles all over the internet, like for instance on MDN.
// swapping variables
let x = 16;
let y = 22;
[y, x] = [x, y]; // x === 22 && y === 16
// using defaults
const x = [2, 3, 4];
const [,, a = 6, b = 8] = x; // a === 4 && b === 8
Assigning directly to an Object Property
One thing I don't usually see anything written about though is assigning to a property of an object using destructuring assignment. I'm talking about something like this:
const x = [2, 3, 4];
const y = {z: 42};
// instead of doing this
y.z = x[1]; // y.z === 3
// we can write:
[,y.z] = x; // y.z === 3 👌 sweet!
Top comments (1)
Thanks. I tried destructuring assignment to properties but ran into troubles. Is anyone able to explain what is going on in the following code, especially why the output is different for the three segments of code.
Code
Output