Lesson

JS Destructuring

10 min reading
Free Course

JavaScript Destructuring: Unpacking Objects and Arrays

JavaScript destructuring assignment extracts properties from objects or items from arrays into distinct variables in one clean expression. Introduced in ES6, it reduces repetitive user.profile.name lookups and makes function signatures self-documenting.

Object and Array Destructuring Basics

  • Object destructuring (const { a, b } = obj): Matches keys by property name regardless of key order. You can rename variables with const { a: localName } = obj and provide defaults with =.
  • Array destructuring (const [first, second] = arr): Matches items by position, skips unwanted items with commas, and swaps two variables in one line ([a, b] = [b, a]).

Practical Destructuring in Functions and Rest Patterns

Combine destructuring with ...rest to separate known fields from remaining properties or tail elements.

const apiResponse = {
  id: 88,
  title: "ES6 Guide",
  author: { name: "Tariq" },
};

// Rename, nested destructuring, and default value
const {
  title: lessonTitle,
  status = "published",
  author: { name: authorName },
} = apiResponse;

console.log({ lessonTitle, status, authorName });

// Array destructuring with rest
const [winner, runnerUp, ...others] = ["Ada", "Linus", "Grace", "Alan"];
console.log({ winner, runnerUp, others });

// Function parameter destructuring with default empty object
function printBadge({ name, role = "member" } = {}) {
  console.log(`${name} [${role}]`);
}
printBadge({ name: "Nadia" });

Common Mistakes to Avoid

  • Destructuring null or undefined: const { id } = user throws a TypeError if user is null or undefined. Guard with const { id } = user ?? {};.
  • Passing an object argument without = {} default: Calling printBadge() with no arguments crashes unless you default the parameter to {}.
  • Using default fallback when the value is null: Destructuring defaults (status = "draft") trigger only when the property is undefined, not when it is null.

Frequently Asked Questions

Can I swap two variables without a temporary variable?

Yes, write [left, right] = [right, left]; using array destructuring on let variables.

How do I ignore the first element of an array when destructuring?

Leave an empty slot before the comma: const [, secondItem] = list;.

Does destructuring mutate the original object or array?

No, destructuring only reads values into new variables (or copies remaining keys into a shallow ...rest object/array).

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Try it Yourself

Experiment with the code from this lesson in our interactive playground.

Open Playground
JavaScript Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum