Destructuring
Destructuring allows you to extract values from objects or arrays into distinct variables.
const person = {
name: 'John Doe',
age: 30,
city: 'New York'
};
const { name, age } = person;
console.log(name, age); // Output: John Doe 30
const numbers = [1, 2, 3, 4, 5];
const [first, second, ...rest] = numbers;
console.log(first, second, rest); // Output: 1 2 [3, 4, 5]
In the example above, object destructuring is used to extract the name and age properties from the person object. Array destructuring is used to assign the first two elements of the numbers array to first and second, while the rest of the elements are captured in the rest array.
No comments:
Post a Comment