JAVASCRIPT DESTRUCTURING
JavaScript destructuring is a convenient way to extract values from arrays or properties from
objects into distinct variables. It makes your code cleaner and more readable.
Array Destructuring
You can extract values from arrays like this:
const numbers = [1, 2, 3]; // Basic destructuring
const [first, second] = numbers;
console.log(first); // 1
console.log(second); // 2
You can also skip elements:
const [one, , three] = numbers;
console.log(one); // 1
console.log(three); // 3
Object Destructuring
For objects, it works similarly:
const person = { name: 'Alice', age: 30, }; // Basic destructuring
const { name, age } = person;
console.log(name); // Alice
console.log(age); // 30
Default Values
You can set default values if a property is undefined:
const { name = 'Guest', age = 25 } = { name: 'Eve' };
console.log(name); // Eve
console.log(age); // 25
Conclusion
Destructuring is a powerful feature in JavaScript that helps you work with complex data
structures more easily. It’s widely used in modern JavaScript development, especially with
frameworks like React.