Js Destructuring in JavaScript
? JavaScript Destructuring
Destructuring is a convenient way to extract values from arrays or objects into variables.
1. Array Destructuring
const arr = [1, 2, 3];const [a, b, c] = arr;console.log(a, b, c); // 1 2 3// Skip elementsconst [first, , third] = arr;console.log(first, third); // 1 32. Object Destructuring
const person = { name: "Alice", age: 30, city: "New York"};const { name, age } = person;console.log(name, age); // Alice 30// Rename variablesconst { city: location } = person;console.log(location); // New York// Default valuesconst { country = "USA" } = person;console.log(country); // USA3. Nested Destructuring
const user = { id: 1, profile: { name: "Bob", social: { twitter: "@bob" } }};const { profile: { name, social: { twitter } }} = user;console.log(name, twitter); // Bob @bob4. Function Parameters Destructuring
function greet({ name, age }) { console.log(`Hello, ${name}. You are ${age} years old.`);}greet({ name: "Carol", age: 25 });Want me to show you destructuring with rest parameters, or how to destructure function return values?