Skip to content

Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy
JavaScript

JavaScript: Use Destructuring to Extract Values Cleanly

- 30.03.26 - ErcanOPAK

📦 Unpack Like Python

Accessing nested properties? const x = obj.prop.nested? Verbose. Destructuring extracts values from objects and arrays elegantly. One line replaces five.

Object Destructuring

const user = {
  name: 'Alice',
  age: 30,
  email: 'alice@example.com',
  address: {
    city: 'New York',
    country: 'USA'
  }
};

// ❌ Old way
const name = user.name;
const age = user.age;
const email = user.email;

// ✅ Destructuring
const { name, age, email } = user;

console.log(name);  // 'Alice'
console.log(age);   // 30
console.log(email); // 'alice@example.com'

🎯 Advanced Object Destructuring

// Rename variables
const { name: userName, age: userAge } = user;
console.log(userName);  // 'Alice'

// Default values
const { name, role = 'guest' } = user;
console.log(role);  // 'guest' (not in object)

// Nested destructuring
const { address: { city, country } } = user;
console.log(city);  // 'New York'

// Rest operator (collect remaining properties)
const { name, ...rest } = user;
console.log(rest);  // { age: 30, email: '...', address: {...} }

// Function parameters
function greet({ name, age }) {
  console.log(`Hello ${name}, you are ${age}`);
}
greet(user);  // 'Hello Alice, you are 30'

Array Destructuring

const colors = ['red', 'green', 'blue', 'yellow'];

// ❌ Old way
const first = colors[0];
const second = colors[1];

// ✅ Destructuring
const [first, second] = colors;
console.log(first);   // 'red'
console.log(second);  // 'green'

// Skip elements
const [, , third] = colors;
console.log(third);  // 'blue'

// Rest operator
const [primary, ...secondary] = colors;
console.log(primary);    // 'red'
console.log(secondary);  // ['green', 'blue', 'yellow']

// Default values
const [a, b, c, d, e = 'default'] = colors;
console.log(e);  // 'default' (array only has 4 items)

Swap Variables

let a = 1;
let b = 2;

// ❌ Old way (needs temp variable)
let temp = a;
a = b;
b = temp;

// ✅ Destructuring swap
[a, b] = [b, a];

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

// No temp variable needed!

📡 Real-World: API Responses

// API returns complex object
const response = {
  data: {
    user: {
      id: 123,
      profile: {
        name: 'Bob',
        avatar: 'avatar.jpg'
      },
      stats: {
        followers: 1000,
        following: 500
      }
    }
  },
  meta: {
    status: 200
  }
};

// ❌ Old way - Multiple lines
const userId = response.data.user.id;
const userName = response.data.user.profile.name;
const avatar = response.data.user.profile.avatar;
const followers = response.data.user.stats.followers;

// ✅ Destructuring - One line!
const {
  data: {
    user: {
      id: userId,
      profile: { name: userName, avatar },
      stats: { followers }
    }
  }
} = response;

console.log(userId, userName, avatar, followers);
// 123, 'Bob', 'avatar.jpg', 1000

React Component Props

// ❌ Old way
function UserCard(props) {
  return (
    

{props.name}

{props.email}

); } // ✅ Destructuring in parameters function UserCard({ name, email, avatar }) { return (

{name}

{email}

); } // With default values function UserCard({ name, email, avatar = 'default-avatar.png', role = 'user' }) { return
...
; }

✅ Common Use Cases

  • Function params: Extract only needed properties
  • API responses: Pull data from nested JSON
  • Import statements: Named imports are destructuring
  • React hooks: const [state, setState] = useState()
  • Module exports: Extract specific functions

💡 Pro Tips

  • Computed property names: const { [key]: value } = obj
  • Don’t overdo nesting: Deep destructuring is hard to read
  • Use TypeScript: Get autocomplete for destructured properties
  • Combine with spread: const newObj = { …user, age: 31 }

🎯 Cheat Sheet

Pattern Example
Basic object const { a, b } = obj
Rename const { a: newName } = obj
Default value const { a = 5 } = obj
Nested const { a: { b } } = obj
Rest const { a, ...rest } = obj
Array const [a, b] = arr

“Refactored React components to use destructuring. 50 lines of ‘const x = props.x’ became 1 line. Code so much cleaner. Should’ve learned this years ago.”

— React Developer

Related posts:

Abort Fetch Requests to Prevent UI Race Conditions

Debounce vs Throttle in JavaScript: When to Use Which (With Real Examples)

Javascript Refresh and CountDown Timer

Post Views: 4

Post navigation

HTML: Use Semantic HTML5 Elements for Better SEO and Accessibility
Ajax: Use Fetch API Instead of XMLHttpRequest for Clean Async Requests

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

April 2026
M T W T F S S
 12345
6789101112
13141516171819
20212223242526
27282930  
« Mar    

Most Viewed Posts

  • Get the User Name and Domain Name from an Email Address in SQL (950)
  • How to add default value for Entity Framework migrations for DateTime and Bool (858)
  • Get the First and Last Word from a String or Sentence in SQL (836)
  • How to select distinct rows in a datatable in C# (805)
  • How to make theater mode the default for Youtube (751)
  • Add Constraint to SQL Table to ensure email contains @ (578)
  • How to enable, disable and check if Service Broker is enabled on a database in SQL Server (564)
  • Average of all values in a column that are not zero in SQL (531)
  • How to use Map Mode for Vertical Scroll Mode in Visual Studio (489)
  • Find numbers with more than two decimal places in SQL (447)

Recent Posts

  • C#: Use Init-Only Setters for Immutable Objects After Construction
  • C#: Use Expression-Bodied Members for Concise Single-Line Methods
  • C#: Enable Nullable Reference Types to Eliminate Null Reference Exceptions
  • C#: Use Record Types for Immutable Data Objects
  • SQL: Use CTEs for Readable Complex Queries
  • SQL: Use Window Functions for Advanced Analytical Queries
  • .NET Core: Use Background Services for Long-Running Tasks
  • .NET Core: Use Minimal APIs for Lightweight HTTP Services
  • Git: Use Cherry-Pick to Apply Specific Commits Across Branches
  • Git: Use Interactive Rebase to Clean Up Commit History Before Merge

Most Viewed Posts

  • Get the User Name and Domain Name from an Email Address in SQL (950)
  • How to add default value for Entity Framework migrations for DateTime and Bool (858)
  • Get the First and Last Word from a String or Sentence in SQL (836)
  • How to select distinct rows in a datatable in C# (805)
  • How to make theater mode the default for Youtube (751)

Recent Posts

  • C#: Use Init-Only Setters for Immutable Objects After Construction
  • C#: Use Expression-Bodied Members for Concise Single-Line Methods
  • C#: Enable Nullable Reference Types to Eliminate Null Reference Exceptions
  • C#: Use Record Types for Immutable Data Objects
  • SQL: Use CTEs for Readable Complex Queries

Social

  • ErcanOPAK.com
  • GoodReads
  • LetterBoxD
  • Linkedin
  • The Blog
  • Twitter
© 2026 Bits of .NET | Built with Xblog Plus free WordPress theme by wpthemespace.com