#1 JavaScript Tricks for Cleaner Code with : 💡Object Destructuring
Tags: javascript, webdev, programming, beginners
Published: 2023-10-26 07:35:50


![Welcome](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/02mmsjcowq9gaucvdt3g.gif)

Hello Guys,

Welcome to [Top 10 Javascript tricks for clean code](https://dev.to/todayscode14/the-top-10-javascript-tricks-for-cleaner-code-422b) 

`Series #1` : **" Object Destructuring "**

Its me [Md Taqui Imam](https://bit.ly/mdTaquiImam).
 **Today In this Blog series #1** i will try to Go in-dept on "Object Destructuring" as possible with examples .

{% cta https://github.com/taqui-786 %}Follow me in Github{% endcta %}

> So. Let's Get Started🔥.

## ❓ What is Object Destructuring?

Object destructuring is a cool feature in modern JavaScript that can help make your code cleaner and easier to read. Here are some tips for using object destructuring like a pro!

## 📚 What to use Object Destructuring?

Destructuring allows you to unpack values from arrays or properties from objects into distinct variables. 

For example:

```js
const person = {
  firstName: "John",
  lastName: "Doe",
  age: 30
};

// Without destructuring
const firstName = person.firstName; 
const lastName = person.lastName;
const age = person.age;

// With destructuring
const {firstName, lastName, age} = person;
```

So with destructuring we can extract multiple properties into variables in one line instead of doing it manually. Pretty sweet!

## 🍭 Common Uses for Object Destructuring

There are a few handy ways you can use object destructuring to write cleaner code:

### 1. Extracting function parameters

```js
// Without destructuring 
function getFullName(user) {
  const firstName = user.firstName;
  const lastName = user.lastName;
  
  return `${firstName} ${lastName}`;
}

// With destructuring
function getFullName({firstName, lastName}) {
  return `${firstName} ${lastName}`;  
}

getFullName({firstName: "John", lastName: "Doe"});
```

No more repetitive code to extract firstName and lastName!

### 2. Destructuring return values 

```js
// Without destructuring
function calculate() {
  return {result: 10}; 
}

const obj = calculate();
const result = obj.result;

// With destructuring
function calculate() {
  return {result: 10};
}

const {result} = calculate();
```

Unpack what you need directly into variables.

### 3. Renaming extracted variables

You can also rename the extracted variables by doing:

```js
const {firstName: fn, lastName: ln} = person;
```

This reassigns firstName to a variable called fn instead. Helpful for avoiding naming conflicts!

### 4. Setting default values

You can set default values if the extracted property doesn't exist:

```js 
const {middleName = "N/A"} = person;
```

Now middleName will be "N/A" if it's undefined on person.

## 🏁 Destructuring is Your Friend!

There are many other neat tricks for destructuring objects and arrays in JavaScript. But these examples should give you a good starter kit to start writing cleaner code.

Give it a try and see how destructuring can tidy up your code !

---


## Bonus 🎉:
 

## 10 use cases for JavaScript object destructuring with examples 🎉


### 1. Assign Variables from Properties

```js
const user = {
  name: 'John Doe',
  age: 30
};

const { name, age } = user;

console.log(name); // John Doe 
console.log(age); // 30
```

This allows us to extract properties from an object and assign them to variables in one line.

### 2. Assign with Alias

```js 
const user = {
  name: 'John Doe',
  id: 123
};

const { name: userName, id: userId } = user;

console.log(userName); // John Doe
console.log(userId); // 123 
```

We can alias the properties when destructuring to give them different variable names.

### 3. Assign Default Values 

```js
const user = {
  name: 'John Doe'
};

const { name, age = 30 } = user;

console.log(name); // John Doe
console.log(age); // 30
```

Default values allow falling back to something if the property is undefined.

### 4. Nested Objects

```js
const user = {
  name: 'John Doe',
  profile: {
    age: 30,
    location: 'Canada' 
  }
};

const { profile: { age, location } } = user;

console.log(age); // 30 
console.log(location); // Canada
```

We can access nested properties by destructuring nested objects.

### 5. Arrays

```js
const [a, b] = [1, 2];

console.log(a); // 1
console.log(b); // 2
```

We can destructure arrays in the same way as objects.

### 6. Return Multiple Values 

```js
function calc() {
  return {
    sum: 1 + 2,
    product: 3 * 4   
  };
}

const { sum, product } = calc();

console.log(sum); // 3
console.log(product); // 12
```

Destructuring allows functions to return multiple values which we can assign to variables.

### 7. Parameter Handling

```js
function add({ a, b }) {
  return a + b;
}

add({ a: 1, b: 2 }); // 3
``` 

When calling functions, we can destructure parameters passed in.

### 8. Omit Properties

```js 
const user = { 
  id: 42,
  isAdmin: false,
  name: 'John'
};

const { id, ...userWithoutId } = user;

console.log(id); // 42
console.log(userWithoutId); // {isAdmin: false, name: "John"}
```

We can omit properties during destructuring.

### 9. String Destructuring

```js
const [first, second] = 'hello';

console.log(first); // 'h' 
console.log(second); // 'e'
```

Strings can also be destructured like arrays.

### 10. Destructure Functions

```js
const add = ({a, b}) => a + b;

add({a: 1, b: 2}); // 3
```

Function parameters can be destructured for convenient usage.

---

> Thankyou for reading this blog,

i hope you find this helpful and learned something new 😊

**See you next series of Javascript clean Coding Tricks **

Don't Forget to Like 💖🦄🔥

## Happy Coding 👋