Array & Object Destructuring
Array and object destructuring can truly change the way we write a lot of our code. They greatly clean up our code by reducing the number of lines we need to write when working with objects and arrays. We'll cover their nuances and show how they work in every situation.
We'll cover the following...
Array and object destructuring can truly change the way we write a lot of our code. Let’s dive right in and explain by example.
Before, to get values out of an array or object, we’d have to use direct assignment.
var arr = [1, 2, 3];var one = arr[0];var two = arr[1];var three = arr[2];console.log(one, two, three); // -> 1 2 3// ---------------------------------------var obj = {key1: 'val1',key2: 'val2'};var key1 = obj.key1;var key2 = obj.key2;console.log(key1, key2); // -> val1 val2
Now we have a new tool.
const arr = [1, 2, 3];const [one, two, three] = arr;console.log(one, two, three); // -> 1 2 3// ---------------------------------------const obj = {key1: 'val1',key2: 'val2'};const { key1, key2 } = obj;console.log(key1, key2); // -> val1 val2
We’ve just witnessed a new way to assign values to variables. It’s as simple as following the pattern shown. It’s called destructuring and can be thought of as breaking down the object/array into its individual components.
Line 2 above pulls the numbers 1
, 2
, and 3
out of the array and gives them to the variables one
, two
, ...