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

推荐订阅源

Hacker News: Ask HN
Hacker News: Ask HN
IT之家
IT之家
S
SegmentFault 最新的问题
T
Tailwind CSS Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
博客园 - 司徒正美
J
Java Code Geeks
博客园 - 聂微东
雷峰网
雷峰网
阮一峰的网络日志
阮一峰的网络日志
The Cloudflare Blog
博客园_首页
大猫的无限游戏
大猫的无限游戏
博客园 - 三生石上(FineUI控件)
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
博客园 - 【当耐特】
腾讯CDC
Apple Machine Learning Research
Apple Machine Learning Research
酷 壳 – CoolShell
酷 壳 – CoolShell
V
V2EX
宝玉的分享
宝玉的分享
小众软件
小众软件
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Hugging Face - Blog
Hugging Face - Blog
月光博客
月光博客
NISL@THU
NISL@THU
T
The Exploit Database - CXSecurity.com
C
CXSECURITY Database RSS Feed - CXSecurity.com
WordPress大学
WordPress大学
有赞技术团队
有赞技术团队
Blog — PlanetScale
Blog — PlanetScale
aimingoo的专栏
aimingoo的专栏
L
LINUX DO - 热门话题
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
F
Fortinet All Blogs
博客园 - Franky
L
Lohrmann on Cybersecurity
S
Secure Thoughts
量子位
V
Vulnerabilities – Threatpost
Last Week in AI
Last Week in AI
博客园 - 叶小钗
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
L
LINUX DO - 最新话题
I
InfoQ
C
CERT Recently Published Vulnerability Notes
Security Archives - TechRepublic
Security Archives - TechRepublic
P
Proofpoint News Feed
G
GRAHAM CLULEY
Cisco Talos Blog
Cisco Talos 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 Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
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. 🚀