JavaScript Destructuring Assignment Explained
What is destructuring?
Destructuring is JavaScript expression that allows you to assign properties of an array or object to variables using syntax that look similar to array or object literals.
Let’s look at a simple example below. We have a person with a first name, last name, and a birthday.
const person = {firstName: 'John',lastName: 'Smith',birthDate: '3/12/1950'}//if we wanted assign firstName to John, lastName to Smith, and birthDate to 3/12/1950 we would have to do so by assigning itconst firstName = person.firstNameconst lastName = person.lastNameconst birthDate = person.birthDate//output belowfirstName // => 'John'lastName // => 'Smith'birthDate // => '3/12/1950'
This way works just fine but you’re having to reassign the name a couple of times to make it work. You can use destructuring to skip a few lines of code to read a property and assign the value without duplicating the property.
const person = {firstName: 'John',lastName: 'Smith',birthDate: '3/12/1950'}//using the same person info we can apply destructuringconst { firstName, lastName, birthDate } = person//output belowfirstName // => 'John'lastName // => 'Smith'birthDate // => '3/12/1950'
This is a better way of assignment because neither the property names nor the object variable is duplicated and also a little easier to read. This is also known as extracting a property.