# Destructuring in JavaScript

Destructuring in javaScript is basic and import concept while writing. It was introduced in ES6 in this blog cover where desctructuring is used ? Before desturing how variable used?

Topic's cover:

1.  What destructuring means
    
2.  Destructuring arrays
    
3.  Destructuring objects
    
4.  Default values
    
5.  Benefits of destructuring
    

## What destructuring means?

Destructuring is a way to get value from array and object. it can pick values from one by one as per requirement. it creates a **shallow copy** nested object or array still has reference of original address.

It is used most of the time when data comes from API and there are multiple key value pair of object so can get specific key from object. Let's see one by one.

### Destructuring array

For `array` destructuring uses square bracket `[]`.

```javascript
const [first, second] = ["Apple", "Banana"];
console.log(first);

//Output: Apple
```

the `first` get value `0` index value and `second` get `1` index value.

```javascript
const [first, , thired] = ["Apple", "Banana", "thired"];
console.log(thired);

//Output: thired
```

This way can skip the element from an array.

```javascript
let num1 = 10;
let num2 = 20;

[num2, num1] = [num1, num2]

console.log("num1",num1);
console.log("num2",num2);
```

With the help of destructuring can swap two variable values.

### Destructuring object

For `object` to destructuring uses curly braces `{}`.

```javascript
const {name, age} = {name: "Rohan", age: 12};
console.log(name)
```

This is the basic example destructur with object. if `key` is not matched with variable so it shows `undefined`. `key` name and variable must be same name.

Now let's see default value and change variable name.

```javascript
const {name: fullName, age} = {name: "Rohan", age: 12};
console.log(fullName);

// Output: Rohan
```

This way can change the variable name but first get data with same `key` name and then change later.

### Default value

```javascript
const {name , age, location = "Delhi"} = {name: "Rohan", age: 12, location: undefined};

console.log(location);
// Delhi
```

This is way of giving default value as a fallback if value is `undefined` so fallback value used.

## Benefits of destructuring

*   It reduces the code of repetition like `user.name` again and again.
    
*   can give fallback value instead of `undefined`.
    
*   get limited elements.
    
*   using with **rest operator (...)** create new object.
