Dimly reminiscent of the idea of pattern matching as used in some functional programming languages, destructuring allows for the unpacking of array values and object properties into distinct variables. If you’re passing objects into functions, destructuring means that you can explicitly state which properties from the argument object you want to use.
To use destructuring, on the LHS of the assignment operator (=) place square brackets for destructuring an array or braces for an object; then, add variable names for the values that you want. For arrays, variables get assigned values based on index order. For objects, you should use the keys from the object, but that’s not strictly necessary.
The following listing details how to destructure an array.
let fst, snd, rest; const data = ['first', 'second', 'third', 'fourth', 'fifth']; [fst, snd, ...rest] = data; 1 [, fst, snd] = data; 2 const shortArr = [1]; [fst, snd = 10] = shortArr; 3 let a = 3, b = 4; [a, b] = [b, a]; 4
Destructuring objects requires a little more care; you need to know what properties the object has so that they can be unpacked.
See the following listing for examples of use.
const obj = {a: 10, b: 100, c: 1000}; const {a, c} = obj; 1 const {a: ten, c: hundred} = obj; 2 const {a, d = 50} = obj; 3 const shape = {type: 'square', sides: {width: 10, height: 10}}; 4 const areaOfSquare = ({side: {width}}) => width * width; 5 areaOfSquare(shape); 6
Destructuring is an operation that can only be applied to the result of assignment, usually for function return values and regular expression matches, but can also be applied in function argument lists and in for ... of iteration. Further examples and information are available at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment.
We use this technique in multiple places in the Loc8r codebase to cut down on the amount of data a function or callback is allowed to work with.
18.191.228.88