Powerful Examples of Destructuring Assignments in JavaScript

Agbo, Daniel Onuoha - Oct 29 - - Dev Community

Destructuring assignment is a syntactic sugar introduced in ES6 that allows you to unpack values from arrays or objects into variables. It can significantly simplify your code and make it more readable.

Destructuring Arrays

Basic Example:

const numbers = [1, 2, 3, 4];
const [first, second, ...rest] = numbers;

console.log(first); // Output: 1
console.log(second); // Output: 2
console.log(rest); // Output: [3, 4]
Enter fullscreen mode Exit fullscreen mode
  • Skipping Elements: You can skip elements by using commas:
const [first, , third] = numbers;
console.log(first, third); // Output: 1 3
Enter fullscreen mode Exit fullscreen mode
  • Nested Arrays: Destructuring can be applied to nested arrays:
const nestedArray = [[1, 2], [3, 4]];
const [[a, b], [c, d]] = nestedArray;
console.log(a, b, c, d); // Output: 1 2 3 4
Enter fullscreen mode Exit fullscreen mode

Destructuring Objects

Basic Example:

const person = { name: 'Alice', age: 30, city: 'New York' };
const { name, age, city } = person;

console.log(name, age, city); // Output: Alice 30 New York
Enter fullscreen mode Exit fullscreen mode
  • Renaming Properties: You can rename properties during destructuring:
const { name: firstName, age, city } = person;
console.log(firstName, age, city); // Output: Alice 30 New York
Enter fullscreen mode Exit fullscreen mode
  • Default Values: Provide default values for properties that might be missing:
const { name, age = 25, city } = person;
console.log(name, age, city); // Output: Alice 30 New York
Enter fullscreen mode Exit fullscreen mode
  • Nested Objects: Destructure nested objects:
const person = { name: 'Alice', address: { street: '123 Main St', city: 'New York' } };
const { name, address: { street, city } } = person;
console.log(name, street, city); // Output: Alice 123 Main St New York
Enter fullscreen mode Exit fullscreen mode

Swapping Variables

Destructuring can be used to swap variables concisely:

let a = 10;
let b = 20;

[a, b] = [b, a];

console.log(a, b); // Output: 20 10
Enter fullscreen mode Exit fullscreen mode

Destructuring Function Parameters

You can destructure function parameters to make them more readable:

function greet({ name, age }) {
  console.log(`Hello, ${name}! You are ${age} years old.`);
}

greet({ name: 'Alice', age: 30 });
Enter fullscreen mode Exit fullscreen mode

By effectively using destructuring assignment, you can write cleaner, more concise, and more readable JavaScript code.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .