DEV Community

James L
James L

Posted on

πŸŽ„JS Advent #7 - Destructuring πŸŽ„

For the month of December I have challenged myself to write 24 articles about some JS concepts up until Xmas.
The seventh installment in this series is about Destructuring.

You can use the destructuring assignment in JS to unpack objects and arrays.

For example:

var obj = {a: 10, b: 20};
const {a, b} = obj;

console.log(a); // 10
console.log(b); // 20

var arr = [10, 20, 30];
const [a,b,c] = arr;

console.log(a); // 10
console.log(b); // 20
console.log(c); // 30
Enter fullscreen mode Exit fullscreen mode

Any properties not present on the array or object will just be undefined:

var obj = {a: 10, b: 20};
const {c} = obj;

console.log(c); // undefined

var arr = [10, 20];
const [a,b,c] = arr;

console.log(c); // undefined
Enter fullscreen mode Exit fullscreen mode

You can also have a default value for each variable which will be used if that property is not present:

var obj = { a: 10, b: 20, d: null };
const { a, b, c = 30, d = 40 } = obj;

console.log(a); // 10
console.log(b); // 20
console.log(c); // 30 - as c is not on obj
console.log(d); // null - will only set to the default if undefined
Enter fullscreen mode Exit fullscreen mode

The spread syntax can be used also when destructuring

var obj = { a: 10, b: 20, c: 30 };
const { a, ...otherProperties } = obj;

console.log(a); // 10
console.log(otherProperties); // { b: 20, c: 30 }

var arr = [10, 20, 30, 40];
const [a, ...others] = arr;

console.log(a); // 10
console.log(others); // [20,30,40]
Enter fullscreen mode Exit fullscreen mode

Top comments (0)