← Back to libraryQuestion 140 of 468
🟨JavaScriptBeginner

Destructuring

📌 Definition:

Destructuring assignment is a syntax that unpacks values from arrays or properties from objects into distinct variables in a single, readable statement.

📖 Detailed Explanation:

Array destructuring pulls values by position: const [a, b] = [1, 2]. Object destructuring pulls by property name: const { name, age } = user. You can set defaults (const { role = 'guest' } = user), rename (const { name: userName } = user), and combine with the rest operator to collect the remainder (const [first, ...others] = list). Destructuring is common in function parameters (function f({ id, name }) {}), in imports, and when returning multiple values. It makes code shorter and communicates intent — which fields you actually use.

🔑 Key Points:
  • Array by position; object by property name
  • Supports defaults, renaming, and nested destructuring
  • Combine with rest (...) to gather remaining items
  • Great for function params and multiple return values
🌍 Real-World Example:

A React/Playwright config: const { baseURL, timeout = 30000 } = testConfig; extracts what the test needs with a sensible default, instead of repeatedly writing testConfig.baseURL and testConfig.timeout.

🎯 Scenario-Based Interview Question:

Swap two variables without a temporary variable, and extract 'city' from const user = { address: { city: 'NYC' } } in one line.