Destructuring Flashcards

1
Q

What is destructuring?

A

Destructuring is a technique that allows you to unpack values from arrays or objects into separate variables. This process involves breaking down complex data structures into simpler parts, making it easier to work with them

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Where can we destructure?

A

**Destructuring patterns can be used at “data sink locations” such as:

Variable declarations:

const [a] = ['x'];
assert.equal(a, 'x');

let [b] = ['y'];
assert.equal(b, 'y');

Assignments:

let b;
[b] = ['z'];
assert.equal(b, 'z');

Parameter definitions:

const f = ([x]) => x;
assert.equal(f(['a']), 'a');

Note that variable declarations include const and let declarations in for-of loops:

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

Output:

0 a
1 b
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How can you destructure an array?

A

With [] brackets:

const hobbies = ["Reading", "Coding", "Hiking"];
const [firstHobby, secondHobby, thirdHobby] = hobbies;
console.log(firstHobby); // Output: Reading
console.log(secondHobby); // Output: Coding
console.log(thirdHobby); // Output: Hiking

Without destructuring, extracting values from an array can be verbose:

const hobbies = ["Reading", "Coding", "Hiking"];
const firstHobby = hobbies[0];
const secondHobby = hobbies[1];
const thirdHobby = hobbies[2];
console.log(firstHobby); // Output: Reading
console.log(secondHobby); // Output: Coding
console.log(thirdHobby); // Output: Hiking
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How can you skip elements when you destructure an array?

A

By placing a comma without a variable name:

const hobbies = ["Reading", "Coding", "Hiking"];
const [firstHobby, , thirdHobby] = hobbies;
console.log(firstHobby); // Output: Reading
console.log(thirdHobby); // Output: Hiking
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How can you do destructure an object?

A

With {}. Object-destructuring lets you batch-extract values of properties via patterns that look like object literals:

const address = {
  street: 'Evergreen Terrace',
  number: '742',
  city: 'Springfield',
  state: 'NT',
  zip: '49007',
};

const { street: s, city: c } = address;
assert.equal(s, 'Evergreen Terrace');
assert.equal(c, 'Springfield');

“Object-destructuring” (exploringjs.com). Retrieved September 24, 2024.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Can you object-destructure a primitive property?

A

Yes. For example you can object-destructure the length property of a string:

const {length: len} = 'abc';
assert.equal(len, 3);

“Object-destructuring” (exploringjs.com). Retrieved September 24, 2024.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Is it possible to object-destructure an array?

A

Yes, same as with regular objects:

const {0:x, 2:y} = ['a', 'b', 'c'];
assert.equal(x, 'a');
assert.equal(y, 'c');

“Object-destructuring” (exploringjs.com). Retrieved September 24, 2024.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

How can you rename a destructured property?

A

With :. For example:

const address = {
  street: 'Evergreen Terrace',
  number: '742',
  city: 'Springfield',
  state: 'NT',
  zip: '49007',
};

const { street: s, city: c } = address;
assert.equal(s, 'Evergreen Terrace');
assert.equal(c, 'Springfield');`
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What are rest properties?

A

In object literals, you can have spread properties. In object patterns, you can have rest properties (which must come last):

const obj = { a: 1, b: 2, c: 3 };
const { a: propValue, ...remaining } = obj; // (A)

assert.equal(propValue, 1);
assert.deepEqual(remaining, {b:2, c:3});

A rest property variable, such as remaining (line A), is assigned an object with all data properties whose keys are not mentioned in the pattern.

remaining can also be viewed as the result of non-destructively removing property a from obj.

“Rest properties” (exploringjs.com). Retrieved September 24, 2024.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is the problem with this code?

let prop;
{prop} = { prop: 'hello' };
assert.equal(prop, 'hello');
A

The JS engine throws a SyntaxError when trying to compile the code. If we object-destructure in an assignment, we are facing a pitfall caused by syntactic ambiguity – you can’t start a statement with a curly brace because then JavaScript thinks you are starting a block.

The workaround is to put the whole assignment in parentheses:

let prop;
({prop} = { prop: 'hello' });
assert.equal(prop, 'hello');
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Does array-destructuring work on iterable objects?

A

Yes, Array-destructuring can be applied to any value that is iterable, not just to Arrays:

{ // Sets are iterable
  const [a, b] = new Set().add('fee').add('fi').add('fo');
  assert.equal(a, 'fee');
  assert.equal(b, 'fi');
}

{ // Maps are iterable
  const [a, b] = new Map().set('one', 1).set('two', 2);
  assert.deepEqual(
    a, ['one',1]
  );
  assert.deepEqual(
    b, ['two',2]
  );
}

{ // Strings are iterable
  const [a, b] = 'hello';
  assert.equal(a, 'h');
  assert.equal(b, 'e');
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What are rest elements?

A

In Array literals, you can have spread elements. In Array patterns, you can have rest elements (which must come last):

const [x, y, ...remaining] = ['a', 'b', 'c', 'd']; // (A)

assert.equal(x, 'a');
assert.equal(y, 'b');
assert.deepEqual(remaining, ['c', 'd']);

A rest element variable, such as remaining (line A), is assigned an Array with all elements of the destructured value that were not mentioned yet.

“Rest elements” (exploringjs.com). Retrieved September 25, 2024.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

How can you swap the values of two variables with array-destructuring?

A

You can use Array-destructuring to swap the values of two variables without needing a temporary variable:

let x = 'a';
let y = 'b';

[x,y] = [y,x]; // swap

assert.equal(x, 'b');
assert.equal(y, 'a');
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What happens if a destructuring pattern part does not match anything?

A

You get undefined.

Object-destructuring and missing properties
If a property in an object pattern has no match on the right-hand side, you get undefined:

const {prop: p} = {};
assert.equal(p, undefined);

Array-destructuring and missing elements

If an element in an array pattern has no match on the right-hand side, you get undefined:

const [x] = [];
assert.equal(x, undefined);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What values can’t be destructured?

A

You can’t object-destructure undefined and null

Object-destructuring only fails if the value to be destructured is either undefined or null. That is, it fails whenever accessing a property via the dot operator would fail too.

> const {prop} = undefined
TypeError: Cannot destructure property 'prop' of 'undefined'
as it is undefined.

> const {prop} = null
TypeError: Cannot destructure property 'prop' of 'null'
as it is null.

You can’t Array-destructure non-iterable values

Array-destructuring demands that the destructured value be iterable. Therefore, you can’t Array-destructure undefined and null. But you can’t Array-destructure non-iterable objects either:

> const [x] = {}
TypeError: {} is not iterable
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

How can you add a default value to a destructure pattern?

A

With =:

Example of default value in a array-destructure pattern:

const [x=1, y=2] = [];

assert.equal(x, 1);
assert.equal(y, 2);

Example of a default value in an object-destructure pattern:

const {first='', last=''} = {};
assert.equal(first, '');
assert.equal(last, '');

It is also possible to rename a variable and assign ad default value:

const {first: f='', last: l=''} = {};
assert.equal(f, '');
assert.equal(l, '');

Neither property key first nor property key last exist in the object that is destructured. Therefore, the default values are used.

“Default values” (exploringjs.com). Retrieved September 27, 2024.

17
Q

Is it possible to nest destructure patterns?

A

Yes, you can also use patterns as assignment targets, which enables you to nest patterns to arbitrary depths:

const arr = [
  { first: 'Jane', last: 'Bond' },
  { first: 'Lars', last: 'Croft' },
];
const [, {first}] = arr; // (A)
assert.equal(first, 'Lars');

Inside the* Array pattern* in line A, there is a nested object pattern at index 1.

Nested patterns can become difficult to understand, so they are best used in moderation.

https://exploringjs.com/js/book/ch_destructuring.html#nested-destructuring