Skip to main content

Command Palette

Search for a command to run...

Destructuring in JavaScript

Write Cleaner, Shorter, and More Readable Code

Updated
3 min readView as Markdown
Destructuring in JavaScript

Introduction

Have you ever written code like this:

const user = {
  name: "Tony",
  age: 24,
  city: "New York"
};

const name = user.name;
const age = user.age;
const city = user.city;

Looks repetitive right?
That's where destructuring comes in

What is Destructuring?

Destructuring is a way to extract values from arrays or objects and assigns them to variables, in a clean and concise way.

Before vs After (Quick Comparison)

Without destructuring

const user = { name: "Tony", age: 24 };

const name = user.name;
const age = user.age;

With Destructuring

const user = { name: "Viraj", age: 24 };

const { name, age } = user;

Same result, less code more clarity.

Destructuring Arrays

Arrays are destructured based on position (index).

Example:

const numbers = [10, 20, 30];

const [first, second, third] = numbers;

console.log(first);  // 10
console.log(second); // 20

Skipping Values:

const numbers = [10, 20, 30];

const [first, , third] = numbers;

console.log(third); // 30

Destructuring Objects

Objects are destructured based on key names.

Example:

const user = {
  name: "Tony",
  age: 24
};

const { name, age } = user;

console.log(name); // Tony

Renaming Variables:

const user = { name: "Tony" };

const { name: username } = user;

console.log(username); // Tony

Default Values

What if a value doesn't exists?

We can assign defaults:

const user = {
  name: "Tony"
};

const { name, age = 18 } = user;

console.log(age); // 18

Real Power: Reducing Repetitive Code

Without Destructuring:

function printUser(user) {
  console.log(user.name);
  console.log(user.age);
}

With Destructuring:

function printUser({ name, age }) {
  console.log(name);
  console.log(age);
}

Cleaner and easier to read.

Benefits of Destructuring

1. Less Code

Write more with fewer lines.

2. Better Readability

Cleaner variable extraction.

3. Avoid Repetition

No need to repeat object names again and again.

4. Easy function parameters

Directly extract needed values

Everyday Analogy

Backpack Example:

Imagine you have a bagpack:

  • Without destructuring = Take out each item one by one manually

  • With destructuring = Open the bag and grab what you need instantly

Suggestion for Learning

  1. Start small

    • Practice with small objects and arrays
  2. Compare Before vs After

    • Always rewrite normal code using destructuring
  3. Use in function

    • Try destructuring in parameters: very useful in real projects
  4. Don't overcomplicate

    • Keep it simple: avoid deeply nested destructuring at first.

Final Thoughts

Destructuring is a small feature with big impact:

  • Makes code cleaner

  • Improves readability

  • Reduces repetition

Once you start using it, you won’t go back