DEV Community

Marvin Roque
Marvin Roque

Posted on

JavaScript Destructuring: Write Less, Do More

Ever find yourself typing user.name, user.email over and over? Let's fix that with destructuring! Here's how to make your JavaScript cleaner and more readable.

Object Destructuring

// Instead of this:
const name = user.name;
const email = user.email;
// Do this:
const { name, email } = user;
// Need different variable names?
const { name: userName, email: userEmail } = user;
Enter fullscreen mode Exit fullscreen mode

Setting Default Values

const user = { name: 'Alex' };
// If age doesn't exist, use 25
const { name, age = 25 } = user;
console.log(age); // 25
Enter fullscreen mode Exit fullscreen mode

Array Destructuring Magic

const colors = ['red', 'blue', 'green'];
// Get first two colors
const [primary, secondary] = colors;
// Skip elements using commas
const [first, , third] = colors;
// Rest operator for remaining items
const [head, ...rest] = colors;
console.log(rest); // ['blue', 'green']
Enter fullscreen mode Exit fullscreen mode

Function Parameters

// Before
function showUser(user) {
  console.log(`${user.name} (${user.age})`);
}
// After
function showUser({ name, age }) {
  console.log(`${name} (${age})`);
}
// With default values
function greet({ name = 'Guest', age = 20 } = {}) {
  console.log(`Hello ${name}!`);
}
Enter fullscreen mode Exit fullscreen mode

Quick Tricks

// Nested objects
const { 
  name, 
  address: { city, country } 
} = user;
// Combine with renaming
const { 
  address: { city: userCity } 
} = user;
// Swap variables
let a = 1, b = 2;
[a, b] = [b, a];
Enter fullscreen mode Exit fullscreen mode

When to Use It

  • Processing API responses (clean up nested JSON data)
  • Configuration objects (extract specific settings)
  • Function parameters (simplify complex parameter objects)
  • Module imports (select specific exports)
  • Data transformation (reshape objects and arrays)
  • Event handling (extract specific properties from event objects)

That's all! Now go make your code cleaner! 🧹✨

Top comments (0)