2

What is Destructuring in ES6 ?

 7 months ago
source link: https://www.geeksforgeeks.org/what-is-destructuring-in-es6/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

What is Destructuring in ES6 ?

Courses

Destructuring in ES6 is a convenient feature that allows you to extract values from arrays or objects and assign them to variables in a more concise and readable way. It simplifies the process of extracting specific data from complex structures.

Destructuring Arrays:

Basic Array Destructuring:

const numbers = [1, 2, 3];

// Destructuring assignment
const [a, b, c] = numbers;

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

Destructuring array with the help of spread operator:

const numbers = [1, 2, 3, 4, 5];

// Skipping the second element
const [first, , third, ...rest] = numbers;

console.log(first); // Output: 1
console.log(third); // Output: 3
console.log(rest); // Output: [4, 5]

Destructuring Objects:

Basic Object Destructuring:

const person = { name: 'John', age: 30 };

// Destructuring assignment
const { name, age } = person;

console.log(name); // Output: John
console.log(age); // Output: 30

Alias (Renaming Variables):

const person = { name: 'John', age: 30 };

// Destructuring assignment with alias
const { name: personName, age: personAge } = person;

console.log(personName); // Output: John
console.log(personAge); // Output: 30

Default Values:

const person = { name: 'John' };

// Destructuring assignment with default value
const { name, age = 25 } = person;

console.log(name); // Output: John
console.log(age); // Output: 25 (default value)

Destructuring Function Parameters:

// Destructuring function parameters
function printPersonDetails({ name, age }) {
console.log(`Name: ${name}, Age: ${age}`);
}

const person = { name: 'Alice', age: 28 };
printPersonDetails(person);
// Output: Name: Alice, Age: 28

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Looking for a place to share your ideas, learn, and connect? Our Community portal is just the spot! Come join us and see what all the buzz is about!

Three 90 Challenge ending on 5th Feb! Last chance to get 90% refund by completing 90% course in 90 days. Explore offer now.
Last Updated : 02 Feb, 2024
Like Article
Save Article
Share your thoughts in the comments

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK