What is destructuring in JavaScript?
Written by Jatin Thacker, Automation Architect · Updated
undefined.This answer is one piece of Chapter 4: Arrays and Objects.
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.
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));ORD-4100 Kochi 19470 not assigned ORD-4100 ORD-4101 ORD-4100 is pending
city after const { city = 'Pune' } = { city: null }?Related questions
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