The power of destructuring in JavaScript
Tags: webdev, beginners, javascript
Published: 2022-06-18 19:40:59

Hello! My name is Jose and this is my very first DEV post! I am currently a Software Engineering student at Flatiron School, or in other words a newbie. My journey thus far has been quite challenging but rewarding and honestly, also fun!

Perhaps you're a beginner as well and are looking to pick up some a trick or two, well you've found the right place! One of the things I love as I continue to learn JavaScript is coming across cool [**shorthand**](https://www.sitepoint.com/shorthand-javascript-techniques/) techniques that help you achieve your goals with more concise code. In this post I will talking about one of my favorites, **destructuring**.

## What is destructuring?
The [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) defines destructuring assignment as follows:

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

Let's explore this with some examples...

---

## Object destructuring
You're probably already familiar with objects and how we can save property values in variables.

Consider the following example:
```javascript
const employee = {
  firstName: "Peter",
  lastName: "Gibbons",
  jobTitle: "Programmer",
  programmingLanguage: "JavaScript"
};

const firstName = employee.firstName;
const lastName = employee.lastName;
const jobTitle = employee.jobTitle;
const programmingLanguage = employee.programmingLanguage;

console.log(firstName); //LOG: "Peter"
console.log(lastName); //LOG: "Gibbons"
console.log(jobTitle); //LOG: "Programmer"
console.log(programmingLanguage); //LOG: "JavaScript"
```
This works perfectly fine and achieves what we want to do, but that's a lot of typing... We have to explicitly name each property with the `employee` object in dot `.` notation, then declare variables accordingly.

But there's a better way, a way that's more concise and just.. cooler looking.

```javascript
const employee = {
  firstName: "Peter",
  lastName: "Gibbons",
  jobTitle: "Programmer",
  programmingLanguage: "JavaScript"
};


const { firstName, lastName, jobTitle, programmingLanguage } = employee;


console.log(firstName); //LOG: "Peter"
console.log(lastName); //LOG: "Gibbons"
console.log(jobTitle); //LOG: "Programmer"
console.log(programmingLanguage); //LOG: "JavaScript"
```
The left side of the expression contains variables that correspond to the properties of the object that we're working with, wrapped in curly braces `{ }`. The right side of the expression is the object itself.

![object destructuring diagram](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hw8g0gur19yr83b9oc8t.png)
######**Source**: https://www.educative.io/answers/what-is-object-destructuring-in-javascript


Pretty cool isn't it? We're able to define multiple variables each corresponding to an object property, all in one line of code.

Now, imagine a scenario where you wanted to declare a variable in advance without initializing it. What would happen if we tried to use destructuring assignment to assign a property value to our variable without using `let` or `const`?

```javascript
let firstName;

const employee = {
  firstName: "Peter",
  lastName: "Gibbons",
  jobTitle: "Programmer",
  programmingLanguage: "JavaScript"
};

{ firstName } = employee;

console.log(firstName); //Uncaught SyntaxError: expected expression, got '='
```
The `let` and `const` keywords are essential to destructuring assignments. Because neither were used, JavaScript tried to interpret what was within our curly braces `{ }` as a block of code.

In this scenario, the correct syntax would be to encase the destructuring expression in parentheses `( )`
```javascript
({ firstName } = employee)

console.log(firstName) //LOG: "Peter"
```

### Creating aliases
Now, what if we want to define some variables with names of our own choosing? Luckily we can do that:

```javascript
const employee = {
  firstName: "Peter",
  lastName: "Gibbons",
  jobTitle: "Programmer",
  programmingLanguage: "JavaScript"
};


const { jobTitle: title, programmingLanguage: language } = employee;


console.log(title); //LOG: "Programmer"
console.log(language); //LOG: "JavaScript"
```
So, as you can see, the syntax is `{ propertyName: alias }`
Note that attempting to access either `jobTitle` or `programmingLanguage` would result in an error.

```javascript
console.log(jobTitle) //Uncaught ReferenceError: jobTitle is not defined
```

---

## Array destructuring
Destructuring is also possible with arrays, and it makes extracting data from an array much more simple.

Fortunately, unlike destructuring assignments with objects, our variable names do not need to match the name of each item:
```javascript
const animals = ["dog", "cat", "bird"];
const [animal1, animal2, animal3] = animals;

console.log(animal1); //LOG: "dog"
console.log(animal2); //LOG: "cat"
console.log(animal3); //LOG: "bird"
```
With array destructuring assignment, we encase our variable(s) in an array literal `[ ]`, each variable maps to the exact position of the array element.

If the number of variables exceed the number of elements in the array, the last variable will simply return undefined.
```javascript
const animals = ["dog", "cat", "bird"];
const [animal1, animal2, animal3, animal4] = animals;

console.log(animal4) //LOG: undefined
```
Also unlike object destructuring, with arrays we can declare variables in advance and initialize later, without the need to wrap our assignment in parentheses:
```javascript
let a, b, c;
const arr = [1, 2, 3];

[a, b, c] = arr

console.log(a) //LOG: 1
console.log(b) //LOG: 2
console.log(c) //LOG: 3
```
###Working with an array returned from a function
Destructuring with an array return value makes syntax more concise:
```javascript
function returnArray() {
   return [1, 2, 3];
}

let a, b, c;
[a, b, c] = returnArray();

console.log(a) //LOG: 1
console.log(b) //LOG: 2
console.log(c) //LOG: 3
```

###Rest parameters
Instead of having to create a variable for every element in an array, rest parameters allow you to work with arrays with an indefinite number of elements. The syntax is similar to that of the [spread operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax). The elements that are 'left over' are collected into another array:
```javascript
let a, b, rest;

[a, b, ...rest] = [10, 20, 30, 40, 50]

console.log(a) //LOG: 10
console.log(b) //LOG: 20
console.log(rest) //LOG: Array [30, 40, 50]
```

---

There you have it. Go ahead and use these in your next project; make your code more concise, and your life easier!