惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园 - Franky
有赞技术团队
有赞技术团队
宝玉的分享
宝玉的分享
雷峰网
雷峰网
Hugging Face - Blog
Hugging Face - Blog
V
V2EX
大猫的无限游戏
大猫的无限游戏
博客园 - 司徒正美
D
Docker
T
The Blog of Author Tim Ferriss
罗磊的独立博客
博客园 - 叶小钗
酷 壳 – CoolShell
酷 壳 – CoolShell
Blog — PlanetScale
Blog — PlanetScale
月光博客
月光博客
J
Java Code Geeks
Jina AI
Jina AI
博客园 - 【当耐特】
C
Check Point Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
腾讯CDC
Last Week in AI
Last Week in AI
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
V
Visual Studio Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Destructuring in JavaScript
Akash Kumar · 2026-06-26 · via DEV Community

"Destructuring is JavaScript's way of letting you unpack what you need and leave the rest behind."


Introduction

You've worked with arrays and objects in JavaScript. You know how to access their values. But have you noticed how repetitive it gets?

const user = { name: "Alice", age: 28, city: "Delhi" };

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

Three lines. Three times you wrote user.something. Now imagine doing this for an object with ten properties. Or doing it across dozens of files.

Destructuring is JavaScript's answer to that repetition. It's a concise syntax that lets you extract values from arrays and objects directly into variables — in a single line. No dot notation chains. No index lookups. Just clean, readable assignments.


1. What Does Destructuring Mean?

Destructuring means pulling values out of a data structure and binding them to named variables, using a syntax that mirrors the shape of the data itself.

The key insight: instead of describing where to put things (left side) and then going to fetch them (right side), destructuring lets you describe the shape of what you expect on the left — and JavaScript fills in the values from the right.

// Traditional access — fetch and assign one by one
const name = user.name;
const age  = user.age;

// Destructuring — describe the shape, get the values
const { name, age } = user;

Both do the same thing. The destructured version is just less noise.

Destructuring works on two kinds of data structures in JavaScript: objects and arrays. The syntax is slightly different for each, and for good reason.


2. Destructuring Arrays

Array destructuring uses square brackets [] on the left side of the assignment. Values are extracted by position — the first variable gets index 0, the second gets index 1, and so on.

Before vs. After

const colors = ["red", "green", "blue"];

// ❌ Before — manual index access
const first  = colors[0];
const second = colors[1];
const third  = colors[2];

// ✅ After — array destructuring
const [first, second, third] = colors;

ARRAY DESTRUCTURING — POSITIONAL MAPPING

colors  →  [ "red",  "green",  "blue" ]
                ↓        ↓        ↓
            [first, second,  third ]

first  = "red"
second = "green"
third  = "blue"

Skipping Elements

You're not forced to take every value. Leave a gap with a comma to skip positions you don't need.

const scores = [95, 82, 76, 61, 54];

// Only want first and third — skip the second
const [gold, , bronze] = scores;

console.log(gold);   // 95
console.log(bronze); // 76

The Rest Element

Capture the remaining items into a new array using the rest syntax (...).

const [top, ...rest] = [1, 2, 3, 4, 5];

console.log(top);  // 1
console.log(rest); // [2, 3, 4, 5]

Swapping Variables

One elegant trick array destructuring unlocks — swapping two variables without a temporary placeholder:

let a = 1;
let b = 2;

// ❌ Before — needs a temp variable
let temp = a;
a = b;
b = temp;

// ✅ After — one-line swap
[a, b] = [b, a];

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


3. Destructuring Objects

Object destructuring uses curly braces {} on the left side. Unlike arrays, values are matched by property name — not by position — so the order on the left doesn't matter.

Before vs. After

const product = {
  id: 101,
  name: "Mechanical Keyboard",
  price: 4999,
  inStock: true
};

// ❌ Before — repeated property lookups
const id      = product.id;
const name    = product.name;
const price   = product.price;
const inStock = product.inStock;

// ✅ After — object destructuring
const { id, name, price, inStock } = product;

OBJECT DESTRUCTURING  NAME-BASED EXTRACTION

product = {
  id:      101,          ──►  const id      = 101
  name:    "Keyboard",   ──►  const name    = "Keyboard"
  price:   4999,         ──►  const price   = 4999
  inStock: true          ──►  const inStock = true
}

{ id, name, price, inStock } = product
         
  Matches by property name  order doesn't matter

Renaming Variables

Sometimes the property name from the object clashes with an existing variable, or just isn't descriptive enough in context. Use a colon : to rename while destructuring.

const response = { status: 200, data: { user: "Alice" } };

// Rename 'status' → 'statusCode', 'data' → 'payload'
const { status: statusCode, data: payload } = response;

console.log(statusCode); // 200
console.log(payload);    // { user: "Alice" }

// Original names (status, data) no longer exist as variables

Nested Object Destructuring

Objects inside objects can be destructured in one go by mirroring the nested shape.

const user = {
  name: "Akash",
  address: {
    city: "Patna",
    pincode: "800001"
  }
};

// ❌ Before — two-step access
const city    = user.address.city;
const pincode = user.address.pincode;

// ✅ After — nested destructuring
const { name, address: { city, pincode } } = user;

console.log(name);    // "Akash"
console.log(city);    // "Patna"
console.log(pincode); // "800001"

Note that address itself is not created as a variable here — it's only used as a path to reach city and pincode.

Destructuring in Function Parameters

This is one of the most common places you'll see object destructuring in real code. Instead of passing a full object and accessing its properties inside the function, you destructure right in the parameter list.

const order = { id: 42, item: "Laptop", quantity: 2 };

// ❌ Before — access properties inside the function
function printOrder(order) {
  console.log(`Order #${order.id}: ${order.quantity}x ${order.item}`);
}

// ✅ After — destructure in the parameter itself
function printOrder({ id, item, quantity }) {
  console.log(`Order #${id}: ${quantity}x ${item}`);
}

printOrder(order);
// Order #42: 2x Laptop


4. Default Values

What happens when you destructure a property that doesn't exist? You get undefined. Default values let you specify a fallback for exactly that case.

Default Values in Object Destructuring

const settings = { theme: "dark" };

// 'language' doesn't exist in settings
const { theme, language } = settings;
console.log(language); // undefined ← not great

// With a default value
const { theme, language = "en" } = settings;
console.log(language); // "en" ← much better

The default only kicks in when the value is undefined — not when it's null, 0, or "".

const config = { timeout: 0, retries: null };

const { timeout = 5000, retries = 3, debug = false } = config;

console.log(timeout); // 0     ← 0 is a real value, default ignored
console.log(retries); // null  ← null is a real value, default ignored
console.log(debug);   // false ← undefined, so default applies

Default Values in Array Destructuring

const [primary = "blue", secondary = "gray"] = ["red"];

console.log(primary);   // "red"  ← value present, default ignored
console.log(secondary); // "gray" ← nothing at index 1, default applies

Combining Rename and Default

You can rename and set a default at the same time:

const user = {};

// Rename 'name' → 'username', with fallback "Guest"
const { name: username = "Guest" } = user;

console.log(username); // "Guest"


5. Benefits of Destructuring

Destructuring is more than a shorthand — it changes how you think about working with data.

Less Repetition

// ❌ Without destructuring — object name repeated everywhere
function formatAddress(location) {
  return `${location.street}, ${location.city}, ${location.state} ${location.zip}`;
}

// ✅ With destructuring — clean and flat
function formatAddress({ street, city, state, zip }) {
  return `${street}, ${city}, ${state} ${zip}`;
}

Cleaner API Responses

Real-world API responses are often deeply nested. Destructuring lets you pull out exactly what you need without intermediate variables:

// A typical API response
const response = {
  status: 200,
  data: {
    user: {
      id: 7,
      name: "Akash",
      email: "akash@example.com",
      role: "admin"
    }
  }
};

// Extract only what this function cares about
const { data: { user: { name, role } } } = response;

console.log(name); // "Akash"
console.log(role); // "admin"

Readable Function Return Values

Destructuring makes functions that return multiple values feel natural:

function getMinMax(numbers) {
  return {
    min: Math.min(...numbers),
    max: Math.max(...numbers)
  };
}

// Named return values — no [0] and [1] guessing
const { min, max } = getMinMax([3, 1, 9, 4, 7]);

console.log(min); // 1
console.log(max); // 9

Works Beautifully with Loops

const users = [
  { id: 1, name: "Alice", role: "admin" },
  { id: 2, name: "Bob",   role: "viewer" },
  { id: 3, name: "Carol", role: "editor" }
];

// Destructure each object directly in the loop
for (const { name, role } of users) {
  console.log(`${name} is a ${role}`);
}

// Alice is a admin
// Bob is a viewer
// Carol is a editor


Before vs. After: A Full Comparison

WITHOUT DESTRUCTURING                  WITH DESTRUCTURING
─────────────────────────────────────┼───────────────────────────────────────
const name    = user.name;             const {
const age     = user.age;                name,
const city    = user.city;               age,
const country = user.country;            city,
                                         country
                                       } = user;
─────────────────────────────────────┼───────────────────────────────────────
const r = rgb[0];                      const [r, g, b] = rgb;
const g = rgb[1];                    
const b = rgb[2];                    
─────────────────────────────────────┼───────────────────────────────────────
function greet(user) {                 function greet({ name, age = 0 }) {
  const name = user.name;                console.log(`Hi ${name}, ${age}`);
  const age  = user.age || 0;          }
  console.log(`Hi ${name}, ${age}`); 
}                                    
─────────────────────────────────────┼───────────────────────────────────────
 Repetitive property access           Clean, intention-revealing syntax
 More lines for same result           Fewer lines, same result
 Easy to mistype property names       Single source of truth per name
 Verbose function bodies              Self-documenting parameter shapes


Quick Reference

Syntax What It Does
const [a, b] = arr Extract by position from an array
const [a, , c] = arr Skip index 1, take index 0 and 2
const [a, ...rest] = arr Take first, collect the rest
const { x, y } = obj Extract named properties from an object
const { x: newName } = obj Extract and rename x to newName
const { x = 5 } = obj Extract with a fallback default
const { x: n = 5 } = obj Rename and set a default
const { a: { b } } = obj Nested destructuring
function f({ x, y }) {} Destructure in function parameters
[a, b] = [b, a] Swap two variables

Key Takeaways

  • Destructuring extracts values from arrays and objects into named variables
  • Arrays are destructured by position using []; objects are destructured by name using {}
  • Use , to skip positions in array destructuring
  • Use : to rename a property while destructuring an object
  • Use = to set default values when a property might be absent
  • Destructuring works in function parameters, for...of loops, and nested structures
  • Defaults only activate for undefined — not for null, 0, or ""

What's Next?

With destructuring under your belt, these topics will click much faster:

  • Spread and rest operators (...) — the sibling syntax that complements destructuring
  • ES6 modules (import/export) — which use object destructuring syntax to import named exports
  • React props — nearly every React component destructures its props in the parameter list
  • Array methods with destructuring — combining .map(), .filter(), and destructuring for expressive data transformations

Destructuring is one of those features that, once you start using it, you'll wonder how you ever wrote JavaScript without it.


If this helped you write cleaner JavaScript, the natural next read is the spread and rest operator — same concise philosophy, even more use cases. 🚀