What is destructuring assignment?
JavaScriptThe short answer
Destructuring lets you unpack values from arrays or properties from objects into separate variables in a single statement. Instead of accessing values one by one, you extract them all at once. It is used everywhere in modern JavaScript and React.
Object destructuring
const user = { name: 'John', age: 30, city: 'NYC' };// Without destructuringconst name = user.name;const age = user.age;// With destructuringconst { name, age, city } = user;Renaming variables:
const { name: userName, age: userAge } = user;console.log(userName); // "John"Default values:
const { name, role = 'viewer' } = user;console.log(role); // "viewer" — user has no role propertyArray destructuring
const colors = ['red', 'green', 'blue'];const [first, second, third] = colors;// first = "red", second = "green", third = "blue"// Skip elementsconst [, , last] = colors; // "blue"// Swap variableslet a = 1, b = 2;[a, b] = [b, a]; // a = 2, b = 1In function parameters
This is very common in React:
// Destructure props directlyfunction UserCard({ name, age, avatar }) { return ( <div> <img src={avatar} alt={name} /> <h2>{name}</h2> <p>Age: {age}</p> </div> );}// Destructure hook returnsconst [count, setCount] = useState(0);Nested destructuring
const user = { name: 'John', address: { city: 'NYC', zip: '10001' },};const { address: { city },} = user;console.log(city); // "NYC"Interview Tip
Show both object and array destructuring with a quick example each. The function parameter destructuring (React props) is the most practical example. Mentioning variable swapping with array destructuring is a nice bonus.
Why interviewers ask this
Destructuring is used in almost every line of modern JavaScript and React code. Interviewers want to confirm you are comfortable with the syntax and know its common patterns.