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
1const user = { name: 'John', age: 30, city: 'NYC' };
2
3// Without destructuring
4const name = user.name;
5const age = user.age;
6
7// With destructuring
8const { name, age, city } = user;

Renaming variables:

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

Default values:

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

Array destructuring

JAVASCRIPT
1const colors = ['red', 'green', 'blue'];
2
3const [first, second, third] = colors;
4// first = "red", second = "green", third = "blue"
5
6// Skip elements
7const [, , last] = colors; // "blue"
8
9// Swap variables
10let a = 1,
11 b = 2;
12[a, b] = [b, a]; // a = 2, b = 1

In function parameters

This is very common in React:

JAVASCRIPT
1// Destructure props directly
2function UserCard({ name, age, avatar }) {
3 return (
4 <div>
5 <img src={avatar} alt={name} />
6 <h2>{name}</h2>
7 <p>Age: {age}</p>
8 </div>
9 );
10}
11
12// Destructure hook returns
13const [count, setCount] = useState(0);

Nested destructuring

JAVASCRIPT
1const user = {
2 name: 'John',
3 address: { city: 'NYC', zip: '10001' },
4};
5
6const {
7 address: { city },
8} = user;
9console.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.