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 Elegantly

- 22.03.26 - ErcanOPAK

📦 Unpack Data Like a Pro

Accessing nested properties? Writing obj.prop.subprop.value? Destructuring extracts values in one line.

Object Destructuring

// ❌ Old way: Repetitive
const user = { name: 'John', age: 30, email: 'john@example.com' };
const name = user.name;
const age = user.age;
const email = user.email;

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

console.log(name);  // 'John'
console.log(age);   // 30
console.log(email); // 'john@example.com'

🎯 Advanced Object Destructuring

const user = {
  name: 'John',
  age: 30,
  address: {
    city: 'NYC',
    country: 'USA'
  },
  settings: {
    theme: 'dark'
  }
};

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

// Default values
const { role = 'guest' } = user;
console.log(role); // 'guest' (doesn't exist in user)

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

// Rest operator
const { name, ...rest } = user;
console.log(rest); // { age: 30, address: {...}, settings: {...} }

Array Destructuring

// ❌ Old way
const colors = ['red', 'green', 'blue'];
const first = colors[0];
const second = colors[1];

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

// Skip elements
const [primary, , tertiary] = colors;
console.log(tertiary); // 'blue' (skipped green)

// Rest operator
const [head, ...tail] = colors;
console.log(head); // 'red'
console.log(tail); // ['green', 'blue']

// Swap variables (no temp variable needed!)
let a = 1, b = 2;
[a, b] = [b, a];
console.log(a, b); // 2, 1

Function Parameters

🔧 Before Destructuring

function createUser(options) {
  const name = options.name;
  const age = options.age;
  const role = options.role || 'user';
  
  return { name, age, role };
}

createUser({ name: 'John', age: 30 });

✅ With Destructuring

function createUser({ name, age, role = 'user' }) {
  return { name, age, role };
}

createUser({ name: 'John', age: 30 });
// Clean, readable, default value built-in

Real-World Examples

// API Response handling
const response = await fetch('/api/user');
const { data: { user: { name, email } } } = await response.json();

// React props
function UserCard({ name, age, avatar = '/default.png' }) {
  return 
{name}, {age}
; } // Import specific functions import { useState, useEffect } from 'react'; // Array methods const users = [ { id: 1, name: 'John' }, { id: 2, name: 'Jane' } ]; users.forEach(({ id, name }) => { console.log(`${id}: ${name}`); }); // Promise.all results const [users, posts, comments] = await Promise.all([ fetchUsers(), fetchPosts(), fetchComments() ]);

💡 Pro Tips

  • Don’t overdo nesting: 2-3 levels max, then use intermediate variables
  • Use defaults wisely: Prevent undefined errors
  • Rename for clarity: const { id: userId } when context matters
  • Combine with spread: const { id, ...userData } = user

⚠️ Common Gotchas

// ❌ Variable already declared
let name = 'Old';
let { name } = user; // SyntaxError!

// ✅ Use different name or reassign
let { name: newName } = user;

// ❌ Undefined property access
const { address: { city } } = {}; // Error!

// ✅ Safe with optional chaining
const { address: { city } = {} } = user;
// Or
const city = user?.address?.city;

“Refactored codebase to use destructuring. Function signatures became self-documenting. No more guessing what properties objects have. Code reviews faster. Onboarding new devs easier.”

— JavaScript Tech Lead

Related posts:

Ajax — Always Set Timeouts

Silent JSON Parsing Failures

JavaScript — structuredClone() Beats JSON Tricks

Post Views: 6

Post navigation

HTML5: Use Semantic Elements for Better SEO and Accessibility
Ajax: Use AbortController to Cancel Pending Requests

Leave a Reply Cancel reply

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

June 2026
M T W T F S S
1234567
891011121314
15161718192021
22232425262728
2930  
« May    

Most Viewed Posts

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

Recent Posts

  • C#: Use String Interpolation Instead of Concatenation
  • C#: Use Tuples to Return Multiple Values from Methods
  • SQL: Use ISNULL and NULLIF for Smart NULL Handling
  • .NET Core: Use Data Annotations for Model Validation
  • Git: Use Git Clean to Remove Untracked Files
  • Ajax: Add Custom Headers to Fetch Requests
  • JavaScript: Use console.table to Display Arrays as Tables
  • HTML: Use Spellcheck Attribute to Enable Browser Spell Check
  • CSS: Use user-select to Prevent Text Selection
  • Windows 11: Use Snipping Tool for Instant Screenshots

Most Viewed Posts

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

Recent Posts

  • C#: Use String Interpolation Instead of Concatenation
  • C#: Use Tuples to Return Multiple Values from Methods
  • SQL: Use ISNULL and NULLIF for Smart NULL Handling
  • .NET Core: Use Data Annotations for Model Validation
  • Git: Use Git Clean to Remove Untracked Files

Social

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