Curriculum Series

What is destructuring assignment?

What is destructuring assignment?

What is destructuring assignment?

JavaScript

The 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

javascript
const user = { name: 'John', age: 30, city: 'NYC' };
// Without destructuring
const name = user.name;
const age = user.age;
// With destructuring
const { name, age, city } = user;

Renaming variables:

javascript
const { name: userName, age: userAge } = user;
console.log(userName); // "John"

Default values:

javascript
const { name, role = 'viewer' } = user;
console.log(role); // "viewer" — user has no role property

Array destructuring

javascript
const colors = ['red', 'green', 'blue'];
const [first, second, third] = colors;
// first = "red", second = "green", third = "blue"
// Skip elements
const [, , last] = colors; // "blue"
// Swap variables
let a = 1,
b = 2;
[a, b] = [b, a]; // a = 2, b = 1

In function parameters

This is very common in React:

javascript
// Destructure props directly
function UserCard({ name, age, avatar }) {
return (
<div>
<img src={avatar} alt={name} />
<h2>{name}</h2>
<p>Age: {age}</p>
</div>
);
}
// Destructure hook returns
const [count, setCount] = useState(0);

Nested destructuring

javascript
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.

Finished reading?

Mark this topic as solved to track your progress.