JavaScript · The language round
How does destructuring work?
Short answer
Destructuring extracts values from arrays or objects into variables. It supports defaults, renaming, nested patterns and rest elements, and it works in function parameters.
Destructuring is syntax for reading several properties or elements at once. It reduces repetitive access and makes function signatures self-documenting.
const user = {
name: "Asha",
role: "engineer",
address: { city: "Pune" },
};
const { name, role: title, address: { city } } = user;
console.log(name, title, city); // "Asha engineer Pune"
const [first, , third = "n/a"] = [10, 20];
console.log(first, third); // 10 "n/a"Defaults and renaming
const { role = "guest" } = usersupplies a default when the property isundefinedconst { role: title } = userreadsroleinto a variable namedtitleconst { address: { city } } = userdestructures a nested objectconst [first, ...rest] = itemscollects the remaining elements
Defaults only apply to undefined, not to null. A default can also call a function, which is useful for required configuration values.
function greet({ name, role = "guest" }) {
return "Hello " + name + ", " + role;
}
greet({ name: "Asha" }); // "Hello Asha, guest"Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1How do you rename a property while destructuring?
- 2When does a destructuring default apply?
- 3How do you destructure a nested object?
- 4Can you destructure function parameters?
Say it in the interview
Destructuring extracts values from objects or arrays into variables. For objects I can rename a property, provide a default, or follow a nested path. For arrays I can skip positions with commas and collect the rest. Defaults only apply when the value is undefined, not null. It is especially useful in function parameters because it makes the expected shape explicit.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live JavaScript mock interview and get scored feedback on depth, clarity and confidence.