# ES6 Destructuring

Destructuring is a a new technique added in ES6. Simply put, it is a way to assign all the properties from an object or an array to individual variables in a single line of code.

Here is an example of basic destructuring with the values from an array.

let name, num, rest;
[name, num, ...rest] = [
  "bob",
  123,
  "bob@work.org",
  true,
  false,
  "(212)-555-1234"
];
//the value of name will be 'bob'
//the value of num will be 123
//the value of rest will be ['bob@work.org', true, false, '(212)-555-1234']
1
2
3
4
5
6
7
8
9
10
11
12

Here is an example of basic destructuring with an object.

let name, num;
({ name, num } = { name: "Leonard", num: 1234 });
//the variable name will be 'Leonard'
//the variable num will be 1234
1
2
3
4

You can also provide default values for the variables when destructuring an array or object.

let day, month;
({ day = "Monday", month = "January" } = { month: "March" });
//the value of day will be 'Monday'
//the value of month will be 'March'
1
2
3
4

Typically, destructuring is used when passing things to a function. Inside the parentheses that are part of the function name you would place the curly braces or square brackets and then add the variable names that will hold the values being passed to the function.

//destructuring an array
function fred([first, ...rest]) {
  //first will hold "one"
  //rest will be an array holding "two" and "three"
}
let arr = ["one", "two", "three"];
fred(arr);

//destructuring an object
function william({ brother }) {
  //brother will hold "Dean"
  //name gets ignored
}
let obj = { name: "Sam", brother: "Dean" };
william(obj);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

# Using Default values

If you are not sure if the property exists and want to provide a default value for the property, we can do that too.

function shannon({ ref = 0 }) {
  //the first time this is called, ref will be 123
  //the second time this is called, ref will be 0
}
let obj1 = { count: 1, ref: 123 };
let obj2 = { count: 4 };
shannon(obj1);
shannon(obj2);
1
2
3
4
5
6
7
8

# Changing Property Names

If you want to use a variable name that is different than the property name in the object, we can do that too.

function sample({ id: ref = 0 }) {
  //we wanted to extract id from the object but then call it ref
  //and we want to use zero as the default value
  console.log(ref);
}
let obj3 = { count: 45, id: 543 };
sample(obj3);
1
2
3
4
5
6
7

# References and Resources

MDN destructuring (opens new window)

MDN rest parameters (opens new window)

# Return

Back to Week 8 Module Home

Last Updated: 1/5/2021, 11:39:36 PM