Destructuring
Destructuring unpacks values from an array or an object straight into named variables.
Loading visual…
Definition
Destructuring is a syntax for pulling values out of an array or object and binding them to variables in one step, instead of reading each one off by index or property name. Array destructuring matches by position, `const [a, b] = arr` takes the first two elements. Object destructuring matches by property name, `const { name, age } = user` looks up `name` and `age` regardless of where they sit in the object, and `const { name: userName } = user` renames the binding while it unpacks. Both forms support defaults for when a value is missing (`const [a = 1] = []`) and nesting, so a property inside a property, or an element inside an element, can be pulled out in the same pattern (`const { address: { city } } = user`). Destructuring also appears in function parameters, letting a function accept an object and immediately unpack the fields it needs.
Examples
const [first, second] = [10, 20, 30];
// first = 10, second = 20 (30 is ignored)Array destructuring matches by position; extra elements that are not named are simply left alone.
const user = { name: "Ada", age: 30 };
const { name, age: years } = user;
// name = "Ada", years = 30Object destructuring matches by key name and can rename the local variable with a colon.
function greet({ name = "friend" } = {}) {
return `Hi, ${name}`;
}
greet(); // "Hi, friend"
greet({ name: "Ada" }); // "Hi, Ada"A default on the parameter itself covers a missing argument; a default inside the pattern covers a missing property.
Where you see this
- Unpacking named fields straight out of a function's object parameter, like a React component's props.
- Pulling specific values off an API response without writing response.data.user.name repeatedly.
- Swapping two variables in one line: [a, b] = [b, a].
- Reading only the pieces you need from a large config object, with defaults for the rest.