JavaScript Destructuring

JavaScript destructuring is a syntax that allows you to unpack values from arrays or properties from objects into distinct variables. It is a concise and readable way to extract data.

Destructuring Arrays

You can extract values from an array and assign them to variables:

// Array destructuring
const fruits = ['apple', 'banana', 'cherry'];

const [first, second, third] = fruits;

console.log(first); // 'apple'
console.log(second); // 'banana'
console.log(third); // 'cherry'

Destructuring Objects

You can extract values from objects and assign them to variables using their property names:

// Object destructuring
const person = { name: 'Alice', age: 25, city: 'Paris' };

const { name, age, city } = person;

console.log(name); // 'Alice'
console.log(age); // 25
console.log(city); // 'Paris'

You can also rename variables during destructuring:

javascriptCopy code
const { name: fullName, age: years } = person;

console.log(fullName); // 'Alice'
console.log(years); // 25

Default Values

You can assign default values if the value is undefined:

const { country = 'Unknown' } = person;

console.log(country); // 'Unknown'

Nested Destructuring

Destructure nested arrays or objects:

// Nested array destructuring
const nestedArray = [1, [2, 3], 4];
const [a, [b, c]] = nestedArray;

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

// Nested object destructuring
const nestedObject = { outer: { inner: 'value' } };
const { outer: { inner } } = nestedObject;

console.log(inner); // 'value'

Rest in Destructuring

Use the rest operator to capture remaining items:

// Rest in arrays
const numbers = [1, 2, 3, 4];
const [firstNum, ...restNums] = numbers;

console.log(firstNum); // 1
console.log(restNums); // [2, 3, 4]

// Rest in objects
const { name, ...others } = person;

console.log(name); // 'Alice'
console.log(others); // { age: 25, city: 'Paris' }

Function Parameters Destructuring

Destructure directly in function arguments:

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

greet(person); // 'Hello, Alice. You are 25 years old.'

Leave a Reply

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