Skip to contentPlayForge

What is destructuring in JavaScript?

Written by Jatin Thacker, Automation Architect · Updated

Destructuring unpacks properties from an object, or items from an array, into separate variables in one statement. You can rename a property as you unpack it and give it a default for when it is undefined.

You use destructuring in your first Playwright test, perhaps without noticing. In async ({ page }) => { ... }, the curly braces unpack the page property from the object Playwright passes to every test. Fixtures arrive this way, so it is worth knowing what the braces do.

The example starts with an order object. const { id, city, totalInr: total } = order creates three variables at once. The totalInr: total part reads the totalInr property but names the variable total.

const { courier = 'not assigned' } = order shows a default. The order has no courier, so the default is used. MDN is precise about when: the default applies when the property is missing or undefined, and not when it is null.

Arrays destructure by position. const [first, second] = [...] takes the first two order ids and ignores the rest.

The last part is the pattern behind test functions: function describe({ id, status = 'pending' }) unpacks its argument right in the parameter list. Pass the whole order and the function picks out only the fields it needs.

destructuring.mjs
const order = { id: 'ORD-4100', customer: 'Meera Pillai', city: 'Kochi', totalInr: 19470, }; const { id, city, totalInr: total } = order; console.log(id, city, total); const { courier = 'not assigned' } = order; console.log(courier); const [first, second] = ['ORD-4100', 'ORD-4101', 'ORD-4102']; console.log(first, second); function describe({ id, status = 'pending' }) { return `${id} is ${status}`; } console.log(describe(order));
Output
ORD-4100 Kochi 19470
not assigned
ORD-4100 ORD-4101
ORD-4100 is pending
Test yourself
What is city after const { city = 'Pune' } = { city: null }?

AI can write the test now. The job is knowing whether it checks anything. That's what the course teaches, one chapter at a time.

163 lessons · 226 drills · start free

← All questions

Training a team? Talk to us.