DEV Community

Cover image for #1 JavaScript Tricks for Cleaner Code with : 💡Object Destructuring
TAQUI ⭐
TAQUI ⭐

Posted on

#1 JavaScript Tricks for Cleaner Code with : 💡Object Destructuring

Welcome

Hello Guys,

Welcome to Top 10 Javascript tricks for clean code

Series #1 : " Object Destructuring "

Its me Md Taqui Imam.
Today In this Blog series #1 i will try to Go in-dept on "Object Destructuring" as possible with examples .

Follow me in Github

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:

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;
Enter fullscreen mode Exit fullscreen mode

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

// 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"});
Enter fullscreen mode Exit fullscreen mode

No more repetitive code to extract firstName and lastName!

2. Destructuring return values

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

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

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

const {result} = calculate();
Enter fullscreen mode Exit fullscreen mode

Unpack what you need directly into variables.

3. Renaming extracted variables

You can also rename the extracted variables by doing:

const {firstName: fn, lastName: ln} = person;
Enter fullscreen mode Exit fullscreen mode

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:

const {middleName = "N/A"} = person;
Enter fullscreen mode Exit fullscreen mode

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

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

const { name, age } = user;

console.log(name); // John Doe 
console.log(age); // 30
Enter fullscreen mode Exit fullscreen mode

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

2. Assign with Alias

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

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

console.log(userName); // John Doe
console.log(userId); // 123 
Enter fullscreen mode Exit fullscreen mode

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

3. Assign Default Values

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

const { name, age = 30 } = user;

console.log(name); // John Doe
console.log(age); // 30
Enter fullscreen mode Exit fullscreen mode

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

4. Nested Objects

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

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

console.log(age); // 30 
console.log(location); // Canada
Enter fullscreen mode Exit fullscreen mode

We can access nested properties by destructuring nested objects.

5. Arrays

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

console.log(a); // 1
console.log(b); // 2
Enter fullscreen mode Exit fullscreen mode

We can destructure arrays in the same way as objects.

6. Return Multiple Values

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

const { sum, product } = calc();

console.log(sum); // 3
console.log(product); // 12
Enter fullscreen mode Exit fullscreen mode

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

7. Parameter Handling

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

add({ a: 1, b: 2 }); // 3
Enter fullscreen mode Exit fullscreen mode

When calling functions, we can destructure parameters passed in.

8. Omit Properties

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

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

console.log(id); // 42
console.log(userWithoutId); // {isAdmin: false, name: "John"}
Enter fullscreen mode Exit fullscreen mode

We can omit properties during destructuring.

9. String Destructuring

const [first, second] = 'hello';

console.log(first); // 'h' 
console.log(second); // 'e'
Enter fullscreen mode Exit fullscreen mode

Strings can also be destructured like arrays.

10. Destructure Functions

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

add({a: 1, b: 2}); // 3
Enter fullscreen mode Exit fullscreen mode

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 👋

Top comments (0)