Modern JS Talk: Destructuring Assignment
Source: Dev.to

This article was originally published on bmf-tech.com.
It is a reprint from the Innovator Japan Engineers’ Blog.
What is Destructuring Assignment
Destructuring assignment is an expression that extracts data from arrays or objects and assigns it to separate variables. Below are practical examples.
Array Destructuring
let a, b, c;
[a, b, c] = [1, 2, 3];
console.log(a, b, c); // 1 2 3
let color = [1, 2, 3];
const [red, green, yellow] = color;
console.log(red, green, yellow); // 1 2 3Default Values
const [red = 4, green = 5, yellow = 6] = [1, 2]; // yellow is undefined
console.log(red, green, yellow); // 1 2 6Object Destructuring
({ a, b } = { a: 'foo', b: 'bar' }); // assigns 'foo' to a and 'bar' to b
console.log(a, b); // foo barThe surrounding parentheses are required when using object literal destructuring without a declaration, because
{a, b}alone would be parsed as a block statement. See the MDN article for details: Destructuring Assignment - JavaScript | MDN.
Common Usage (e.g., React)
let state = { value: 'foo' };
const { value } = state; // extracts state.value into variable `value`
console.log(value); // fooDirect Object Literal Example
const { value } = { value: 'foo' };
console.log(value); // fooDefault Values
const { foo = 3, bar = 4 } = { foo: 1 }; // `bar` is undefined
console.log(foo, bar); // 1 4Renaming Variables
const { value: value2 } = { value: 'foo' }; // extracts `value` and assigns it to `value2`
console.log(value2); // fooConclusion
We covered JavaScript’s destructuring assignment with concise code examples. The syntax is intuitive once you see it in action, and it’s widely used in modern JavaScript development.