JavaScript lesson · 16 min
JavaScript Destructuring
Pull useful values out of objects and arrays without noisy repeated property access.
What you will practice
- Extract object properties into variables.
- Extract array items by position.
- Use destructuring to make code shorter and clearer.
What this means
Destructuring is a shortcut for taking values out of objects or arrays and giving them names.
With objects, JavaScript matches property names. With arrays, JavaScript uses position: first item, second item, and so on.
Destructuring does not delete values from the original object or array. It only creates convenient variables from them.
If this is your first time seeing this
Destructuring is a shorter way to take values out of objects and arrays.
It does not change the original data. It only creates useful local variables.
Mini glossary
- Destructuring
- Extracting values from an object or array into variables.
- Object pattern
- Using property names in braces, like `{ name, role }`.
- Array pattern
- Using positions in brackets, like `[first, second]`.
Example from everyday life
Destructuring is like unpacking a delivery box. The box still exists, but you take out the charger, cable, and manual so you can use them directly instead of reaching into the box every time.
How it works step by step
- The code creates a `profile` object with nested data.
- `const { name, role } = profile` creates two variables from matching property names.
- `const [firstTool, secondTool] = profile.tools` takes the first two array items.
- The output uses the new local variables instead of repeating `profile.name` and `profile.tools[0]`.
Where you will use this
- A React component often destructures props before rendering.
- An API response can be destructured to pull out only the fields you need.
- A function can destructure options to avoid long chains of `options.something`.
Before you run the code
Destructuring is not required, but it makes code less repetitive when the same object is used several times.
Use it when it improves readability. If destructuring becomes hard to follow, a normal property access can be clearer.
Common beginner mistakes
- Expecting object destructuring to work by position. It works by property name.
- Expecting array destructuring to work by name. It works by position.
- Destructuring too many values at once and making the code harder to read.
Run the code to see console output here.
Code runs locally in a temporary browser worker with a timeout. It is not sent to Lumio analytics or executed on the server.
Try changing this next
- Extract the third tool into a variable named `thirdTool`.
- Add a new property to `profile` and destructure it.
- Rename a destructured property with `{ name: userName }`.