Q11 of 40 · JavaScript

How does destructuring assignment work in JavaScript?

JavaScriptJuniorjavascriptdestructuringes6syntaxobjectsarrays

Short answer

Short answer: Destructuring extracts values from arrays (by position) or object properties (by name) into variables. It supports defaults, renaming, nested destructuring, and rest collection. It is common in function parameters, import statements, and handling API responses.

Detail

Destructuring is a concise way to unpack values from data structures into distinct variables.

Array destructuring: Values are bound by position. You can skip elements with commas, use rest (...), and set defaults.

Object destructuring: Properties are bound by name. You can rename ({ a: localName }), set defaults ({ a = 10 }), and nest: const { address: { city } } = user.

Function parameter destructuring: Extremely common in React, Playwright, and modern Node code — function render({ title, url, icon }) {} is clearer than accessing props.title everywhere.

In test automation: Destructuring is used heavily when handling API responses (const { data, status } = response), Playwright fixture parameters (async ({ page, context }) => {}), and merging config objects.

// EXAMPLE

// Array destructuring
const [first, second, ...rest] = [1, 2, 3, 4, 5];
// first=1, second=2, rest=[3,4,5]

// Skip elements
const [,, third] = [10, 20, 30]; // third=30

// Object destructuring with rename + default + nesting
const { name: fullName, age = 0, address: { city } } = {
  name: "Alice",
  address: { city: "Dublin" },
};
// fullName="Alice", age=0, city="Dublin"

// Playwright fixture — destructuring in params
test("page title", async ({ page }) => {
  await page.goto("https://example.com");
});

// API response
const { data: { userId }, status } = await api.post("/login", creds);

// WHAT INTERVIEWERS LOOK FOR

Fluency with both array and object forms, defaults, renaming, and nested destructuring. Candidates who connect it to Playwright fixtures or React hooks show practical experience.

// COMMON PITFALL

Forgetting that object destructuring binds by name, not position. Also: destructuring `null` or `undefined` throws — always ensure the source value exists, or use optional chaining with a fallback.