Destructuring Flashcards
What is destructuring?
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 Destructuring Works in JavaScript – Explained with Code Examples” (freeCodeCamp.org). Retrieved September 23, 2024.
Where can we destructure?
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
“Where can we destructure?” (exploringjs.com). Retrieved September 23, 2024.
How can you destructure an array?
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 Destructuring Works in JavaScript – Explained with Code Examples” (freeCodeCamp.org). Retrieved September 23, 2024.
How can you skip elements when you destructure an array?
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 Destructuring Works in JavaScript – Explained with Code Examples” (freeCodeCamp.org). Retrieved September 23, 2024.
How can you do destructure an object
?
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.
Can you object-destructure a primitive property?
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.
Is it possible to object-destructure an array?
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 can you rename a destructured property?
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');`
What are rest properties?
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.
What is the problem with this code?
let prop; {prop} = { prop: 'hello' }; assert.equal(prop, 'hello');
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');
“Syntax pitfall: assigning via object destructuring” (exploringjs.com). Retrieved September 25, 2024.
Does array-destructuring work on iterable objects?
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'); }
“Array-destructuring works with any iterable” (exploringjs.com). Retrieved September 25, 2024.
What are rest elements?
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 can you swap the values of two variables with array-destructuring?
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');
“Array-destructuring: swapping variable values” (exploringjs.com). Retrieved September 26, 2024.
What happens if a destructuring pattern part does not match anything?
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);
“What happens if a pattern part does not match anything?” (exploringjs.com). Retrieved September 26, 2024.
What values can’t be destructured?
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
“What values can’t be destructured?” (exploringjs.com). Retrieved September 26, 2024.