18

I have been reading about Destructuring assignment introduced in ES6.

What is the purpose of this syntax, why was it introduced, and what are some examples of how it might be used in practice?

Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
  • does destructuring include the rest/spread operator? – Nick Parsons Feb 09 '19 at 10:37
  • 2
    @NickParsons to me these looks very closely related so i am considering them in this question, feel free to add those also in question – Code Maniac Feb 09 '19 at 10:47
  • Also related: [What do these three dots in React do?](https://stackoverflow.com/questions/31048953). Lots of useful answers on Destructuring, Spread syntax and Rest parameters – adiga Feb 09 '19 at 11:30
  • 1
    It's a great dupe-target reference question, and is highly indexed on Google, that's good enough for me. (searching for destructuring-related syntax questions to link to where the question doesn't contain "destructuring" is a pain) – CertainPerformance Aug 11 '19 at 23:01

3 Answers3

35

What is destructuring assignment ?

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

- MDN

Advantages

A. Makes code concise and more readable.

B. We can easily avoid repeated destructing expression.

Some use cases

1. To get values in variable from Objects,array

let obj = { 'a': 1,'b': {'b1': '1.1'}}
let {a,b,b:{b1}} = obj
console.log('a--> ' + a, '\nb--> ', b, '\nb1---> ', b1)

let obj2 = { foo: 'foo' };
let { foo: newVarName } = obj2;
console.log(newVarName);

let arr = [1, 2, 3, 4, 5]
let [first, second, ...rest] = arr
console.log(first, '\n', second, '\n', rest)


// Nested extraction is possible too:
let obj3 = { foo: { bar: 'bar' } };
let { foo: { bar } } = obj3;
console.log(bar);

2. To combine an array at any place with another array.

let arr = [2,3,4,5]
let newArr = [0,1,...arr,6,7]
console.log(newArr)

3. To change only desired property in an object

let arr = [{a:1, b:2, c:3},{a:4, b:5, c:6},{a:7, b:8, c:9}]

let op = arr.map( ( {a,...rest}, index) => ({...rest,a:index+10}))

console.log(op)

4. To create a shallow copy of objects

let obj = {a:1,b:2,c:3}
let newObj = {...obj}
newObj.a = 'new Obj a'

console.log('Original Object', obj)
console.log('Shallow copied Object', newObj)

5. To extract values from parameters into standalone variables

// Object destructuring:
const fn = ({ prop }) => {
  console.log(prop);
};
fn({ prop: 'foo' });


console.log('------------------');


// Array destructuring:
const fn2 = ([item1, item2]) => {
  console.log(item1);
  console.log(item2);
};
fn2(['bar', 'baz']);


console.log('------------------');


// Assigning default values to destructured properties:

const fn3 = ({ foo="defaultFooVal", bar }) => {
  console.log(foo, bar);
};
fn3({ bar: 'bar' });

6. To get dynamic keys value from object

let obj = {a:1,b:2,c:3}
let key = 'c'
let {[key]:value} = obj

console.log(value)

7. To build an object from other object with some default values

let obj = {a:1,b:2,c:3}
let newObj = (({d=4,...rest} = obj), {d,...rest})
console.log(newObj)

8. To swap values

const b = [1, 2, 3, 4];
[b[0], b[2]] = [b[2], b[0]]; // swap index 0 and 2

console.log(b);

9. To get a subset of an object

10. To do array to object conversion:

const arr = ["2019", "09", "02"],
date = (([year, day, month]) => ({year, month, day}))(arr);

console.log(date);

11. To set default values in function. (Read this answer for more info )

function someName(element, input,settings={i:"#1d252c", i2:"#fff",...input}){
    console.log(settings.i)
    console.log(settings.i2)
}

someName('hello', {i:'#123'})
someName('hello', {i2:'#123'})

12. To get properties such as length from an array, function name, number of arguments etc.

let arr = [1,2,3,4,5];

let {length} = arr;

console.log(length);

let func = function dummyFunc(a,b,c) {
  return 'A B and C';
}

let {name, length:funcLen} = func;

console.log(name, funcLen);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
  • I want to change key names while destructuring. I've an object from some API and the keys make no sense in readable code so I need to take them and make it better/readable: `{message: {WeirdNameKey: 'Neil', MakesNoSense: 'Foo'}}` // Wanted: `const {name: WeirdNameKey, system: MakesNoSense} = message;` I could have sworn I've done this, just to clean things up for use. But, it is not working for me. I just want to both extract and re-key. I could have sworn I've done this before. Is possible? – Neil Gaetano Lindberg Oct 14 '19 at 14:50
  • 1
    @NeilGuyLindberg take a look at the first code snippet in the above answer, you can replace name of key like this, i.e `const {name: newName} = {name: 'some value'}` – Code Maniac Oct 14 '19 at 16:58
  • Thank you @code-maniac. I see I was reversing the op. I just had to flip so I had: `{WeirdNameKey: name}`, and now the code reads well. – Neil Gaetano Lindberg Oct 14 '19 at 19:58
1

It is something like what you have can be extracted with the same variable name

The destructuring assignment is a JavaScript expression that makes it possible to unpack values from arrays or properties from objects into distinct variables. Let's get the month values from an array using destructuring assignment

var [one, two, three] = ['orange', 'mango', 'banana'];

console.log(one); // "orange"
console.log(two); // "mango"
console.log(three); // "banana"

and you can get user properties of an object using destructuring assignment,

var {name, age} = {name: 'John', age: 32};

console.log(name); // John
console.log(age); // 32
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
vishu2124
  • 4,243
  • 2
  • 14
  • 10
0

The De-structured assignment of Javascript is probably an inspiration drawn from Perl language.

This facilitates reuse by avoid writing getter methods or wrapper functions.

One best example that I found very helpful in particular was on reusing functions that return more data than what is required.

If there is a function that returns a list or an array or a json, and we are interested in only the first item of the list or array or json, then we can simply use the de-structured assignment instead of writing a new wrapper function to extract the interesting data item.

Gopinath
  • 4,066
  • 1
  • 14
  • 16