Destructuring
Destructuring is an assignment syntax in JavaScript that makes it easy to unpack values from arrays, or properties from objects, into distinct variables. For example, in the following code snippet, we can easily unpack the values 20
, John
, Doe
, and 2019
into specified variables:
let data2 = [20, "John", "Doe", "2019"]; let [ age1, firstName1, lastName1, year1] = data2
Destructuring makes it possible to assign the element of an array to a variable, unlike the old conventional method of accessing an array element as shown in the following code:
//Old method of accessing an array let data = [20, "John", "Doe", "2019"]; let firstName = data[1]; let age = data[0]; let lastName = data[2]; let year = data[3];
Destructuring also works on objects, as shown in the following code:
let data3 = { Â Â Â Â age: 20, Â Â Â Â firstName: "john", Â Â Â Â lastName: "Doe", Â Â Â Â year: 2019 } let { age2, firstName2, lastName2, year2 } = data3
In object destructuring, notice that we use {}
instead of []
, as used for arrays. This is because the type on the left-hand side must be the same as the type on the right-hand side.
Important note
If we are to use []
while destructuring for an object, we receive an error, showing TypeError, while as a result of using {}
for array destructuring, you might not obtain any error, but the variables will be undefined.
In the next section, we take a look at spread syntax.