Thursday, June 10, 2021

Destructuring

 Destructuring is a convenient way of extracting multiple values from data stored in (possibly nested) objects and Arrays. It can be used in locations that receive data (such as the left-hand side of an assignment). How to extract the values is specified via patterns (read on for examples).

10.1.1 Object destructuring 

Destructuring objects:

const obj = { first: 'Jane', last: 'Doe' };
const {first: f, last: l} = obj;
    // f = 'Jane'; l = 'Doe'

// {prop} is short for {prop: prop}
const {first, last} = obj;
    // first = 'Jane'; last = 'Doe'

Destructuring helps with processing return values:

const obj = { foo: 123 };

const {writable, configurable} =
    Object.getOwnPropertyDescriptor(obj, 'foo');

console.log(writable, configurable); // true true

10.1.2 Array destructuring 

Array destructuring (works for all iterable values):

const iterable = ['a', 'b'];
const [x, y] = iterable;
    // x = 'a'; y = 'b'

Destructuring helps with processing return values:

const [all, year, month, day] =
    /^(\d\d\d\d)-(\d\d)-(\d\d)$/
    .exec('2999-12-31');

10.1.3 Where can destructuring be used? 

Destructuring can be used in the following locations (I’m showing Array patterns to demonstrate; object patterns work just as well):

// Variable declarations:
const [x] = ['a'];
let [x] = ['a'];
var [x] = ['a'];

// Assignments:
[x] = ['a'];

// Parameter definitions:
function f([x]) { ··· }
f(['a']);

You can also destructure in a for-of loop:

const arr = ['a', 'b'];
for (const [index, element] of arr.entries()) {
    console.log(index, element);
}
// Output:
// 0 a
// 1 b

10.2 Background: Constructing data versus extracting data 

To fully understand what destructuring is, let’s first examine its broader context.

JavaScript has operations for constructing data, one property at a time:

const obj = {};
obj.first = 'Jane';
obj.last = 'Doe';

The same syntax can be used to extract data. Again, one property at a time:

const f = obj.first;
const l = obj.last;

Additionally, there is syntax to construct multiple properties at the same time, via an object literal:

const obj = { first: 'Jane', last: 'Doe' };

Before ES6, there was no corresponding mechanism for extracting data. That’s what destructuring is – it lets you extract multiple properties from an object via an object pattern. For example, on the left-hand side of an assignment:

const { first: f, last: l } = obj;

You can also destructure Arrays via patterns:

const [x, y] = ['a', 'b']; // x = 'a'; y = 'b'

Source : https://exploringjs.com/es6/ch_destructuring.html

No comments:

Followers

Link