Destructuring in JavaScript

Published: (April 4, 2026 at 01:46 AM EDT)
2 min read
Source: Dev.to

Source: Dev.to

🧠 What Is Destructuring?

Unpack values from arrays or objects into distinct variables in a single step.

🔹 Destructuring Arrays

Before

const numbers = [10, 20, 30];
const first = numbers[0];
const second = numbers[1];

After

const [first, second, third] = [10, 20, 30];
console.log(first);  // 10
console.log(second); // 20
console.log(third);  // 30

✅ Notes

  • Order matters in arrays.
  • You can skip items with commas:
const [, , third] = [10, 20, 30];
console.log(third); // 30

🔹 Destructuring Objects

Before

const person = { name: "Rahul", age: 22, city: "Delhi" };
const name = person.name;
const age = person.age;

After

const { name, age } = { name: "Rahul", age: 22, city: "Delhi" };
console.log(name); // Rahul
console.log(age);  // 22
  • Order does not matter.
  • Variable names must match property names (or be renamed).
// Renaming
const { name: userName } = { name: "Rahul" };
console.log(userName); // Rahul

🔹 Default Values

If a property might be missing, you can provide a default:

const { name, city = "Unknown" } = { name: "Rahul" };
console.log(city); // Unknown

Nested Destructuring

const user = { name: "Rahul", address: { city: "Delhi" } };
const { name, address: { city } } = user;
console.log(name); // Rahul
console.log(city); // Delhi

⚡ Benefits of Destructuring

  • Less repetitive code
  • Cleaner and more readable
  • Easier to extract nested data
  • Works well with function parameters

🔹 Destructuring in Function Parameters

function greet({ name, city = "Unknown" }) {
  console.log(`Hello ${name} from ${city}`);
}

greet({ name: "Rahul" });
// Hello Rahul from Unknown

Before

function greet(person) {
  const name = person.name;
  const city = person.city || "Unknown";
  console.log(`Hello ${name} from ${city}`);
}

After

function greet({ name, city = "Unknown" }) {
  console.log(`Hello ${name} from ${city}`);
}

✅ Cleaner, shorter, easier to read.


  • Destructuring extracts values from arrays or objects.
  • Arrays → order matters.
  • Objects → variable names must match keys (or be renamed).
  • Supports defaults and nested structures.
  • Ideal for cleaner code and function parameters.
0 views
Back to Blog

Related posts

Read more »

Spread vs Rest Operators in JavaScript

!Cover image for Spread vs Rest Operators in JavaScripthttps://media2.dev.to/dynamic/image/width=1000,height=420,fit=cover,gravity=auto,format=auto/https%3A%2F%...

Synchronous vs Asynchronous JavaScript

JavaScript is single‑threaded, yet it can handle multiple tasks efficiently by using synchronous and asynchronous behavior. What Is Synchronous Code? Synchronou...

Understanding Functions in JavaScript

What is a Function? A function is a block of code designed to perform a specific task. Instead of writing the same code repeatedly, you can write it once insid...