What is destructuring in JavaScript?

JavaScript ES6+ Basic Fresher1–2 Yrs Coding 1 min read

Quick Answer

Destructuring pulls values out of arrays or objects into variables in one statement: const { name, age } = user; or const [first, second] = arr;. You can rename ({ name: userName }), set defaults ({ role = 'guest' }), and nest.

Destructuring is a shorthand for extracting values into variables. const { name, email } = user instead of two lines of user.name. It works on arrays too, positionally. You can rename on the way out, provide a default if the property is missing, and destructure nested structures. Where I use it most is function parameters — taking an options object and destructuring it in the signature with defaults — and pulling a few known props off an object with the rest going into a rest variable.

  • Function parameters: function greet({ name, greeting = 'Hi' }) { ... } — a common way to pass an options object.
  • Swap without a temp: [a, b] = [b, a].
  • Skip array elements with commas: const [, , third] = arr.
  • Combine with rest: const { id, ...rest } = obj.