Quick Answer

JavaScript destructuring is a syntax that unpacks values from arrays and objects into separate variables in one line. Arrays are matched by position using square brackets, while objects are matched by key name using curly braces. You can also set default values, rename variables, reach into nested data, and collect the leftovers with the rest (...) pattern.

What is JavaScript destructuring?

JavaScript destructuring is a short, readable way to pull values out of arrays and objects and drop them straight into variables. Instead of reaching for each item one by one with an index or a dot, you write a pattern on the left that mirrors the shape of your data.

Here is the difference at a glance:

// The old way
const user = { name: 'Aisha', age: 21 };
const name = user.name;
const age = user.age;

// With destructuring
const { name, age } = user;

Both do exactly the same thing, but the second version is one line and easier to read. Destructuring works with arrays, objects, function parameters, and even nested data. Every example below can be pasted into your browser console and run as-is, so try them as you read.

Array destructuring: matching by position

Arrays are ordered, so array destructuring works by position. You put variable names inside square brackets, and each one grabs the item at the matching index.

const colors = ['red', 'green', 'blue'];
const [first, second, third] = colors;

console.log(first);  // 'red'
console.log(second); // 'green'
console.log(third);  // 'blue'

You can skip items you do not need by leaving a gap (an extra comma):

const [ , , third] = colors;
console.log(third); // 'blue'

If there are more variables than values, the extras become undefined:

const [a, b, c, d] = ['x', 'y', 'z'];
console.log(d); // undefined

The key thing to remember: with arrays, names do not matter, order does.

Object destructuring: matching by key name

Objects are unordered, so object destructuring works by key name, not position. The variable names inside the curly braces must match the property names.

const student = { name: 'Ravi', course: 'JavaScript', year: 2 };
const { course, name } = student;

console.log(name);   // 'Ravi'
console.log(course); // 'JavaScript'

Notice we wrote course before name and it still worked. With objects, order is irrelevant. If you ask for a key that does not exist, you get undefined. This is the pattern you will use most, especially for pulling a few properties out of a large object such as an API response or a config file.

FeatureArray destructuringObject destructuring
Matches byPosition (order)Key name
Brackets usedSquare [ ]Curly { }
Rename via colonNoYes
Skip itemsYesJust omit keys
Supports defaultsYesYes

Default values for missing data

Sometimes a value might be missing. You can set a fallback with = so your variable is never accidentally undefined.

const { role = 'student' } = { name: 'Meena' };
console.log(role); // 'student'

const [x = 10, y = 20] = [5];
console.log(x); // 5  (value was present)
console.log(y); // 20 (default kicked in)

Important gotcha: a default only applies when the value is undefined. It does not apply for null, 0, or an empty string.

const { count = 5 } = { count: null };
console.log(count); // null, not 5

const { total = 5 } = { total: undefined };
console.log(total); // 5

Keep this in mind when a server sends back null for empty fields, which is very common.

Renaming variables while you destructure

What if the property name is not the variable name you want? Maybe the key is cryptic, or it clashes with a variable you already have. Use a colon to rename it as you destructure.

const response = { id: 42, nm: 'Priodemy' };
const { nm: siteName } = response;

console.log(siteName); // 'Priodemy'
// console.log(nm);    // ReferenceError: nm is not defined

Read nm: siteName as "take the nm property and store it in a variable called siteName." After this line, the original key name (nm) is not a variable. You can also combine renaming with a default value:

const { nm: siteName = 'Guest' } = {};
console.log(siteName); // 'Guest'

Nested destructuring for deeper data

Data often comes nested, an object inside an object, or an array inside an object. You can reach into those layers by matching the shape.

const student = {
  id: 1,
  address: { city: 'Pune', pin: '411001' }
};

const { address: { city } } = student;
console.log(city); // 'Pune'

Here address: { city } means "go into address, then pull out city." One caveat: this does not create an address variable, only city. If you want both, list them:

const { address, address: { city } } = student;
console.log(city);    // 'Pune'
console.log(address); // { city: 'Pune', pin: '411001' }

Nested destructuring is handy, but avoid going more than two levels deep, it gets hard to read fast.

The rest pattern: collect everything else

The rest pattern (...) collects "everything else" into a new array or object. It is the opposite of picking single values, you grab a few and bundle up the remainder.

const [head, ...tail] = [1, 2, 3, 4];
console.log(head); // 1
console.log(tail); // [2, 3, 4]

With objects, the rest gathers the leftover properties into a fresh object:

const user = { id: 1, name: 'Ravi', age: 20 };
const { id, ...details } = user;

console.log(id);      // 1
console.log(details); // { name: 'Ravi', age: 20 }

This is a clean way to separate one property from the rest. The rest element must always be last in the pattern, otherwise you get a syntax error.

Real uses: props and swapping variables

Destructuring shines in two everyday situations.

Pulling props from function parameters

Instead of accepting a whole object and reading obj.name, obj.role inside, destructure right in the parameter list. This is extremely common in React and Node.js code.

function greet({ name, role = 'student' }) {
  return `Hi ${name}, you are a ${role}.`;
}

console.log(greet({ name: 'Aisha' }));
// 'Hi Aisha, you are a student.'

Swapping two variables

Before destructuring, a swap needed a temporary variable. Now it is one line:

let a = 1;
let b = 2;

[a, b] = [b, a];

console.log(a); // 2
console.log(b); // 1

One small catch: if the line above the swap has no semicolon, JavaScript may glue the two lines together. Ending statements with semicolons (as shown) keeps you safe. Want to practise these patterns inside real projects? Our free JavaScript course covers destructuring and much more, step by step.

Common gotchas and our recommendation

A few things trip up beginners:

  • Destructuring null or undefined throws. const { a } = null; gives a TypeError. Guard it with a fallback object: const { a } = data || {};
  • Defaults only cover undefined, not null, as we saw earlier.
  • Assigning to existing variables needs parentheses. If you destructure without let or const, wrap it: ({ a } = obj); Otherwise the leading { looks like a code block and errors.

Our recommendation: reach for object destructuring whenever a function takes an options object or you use two or more properties from the same object. Use array destructuring for fixed-shape data like coordinates or swaps. Keep nesting shallow, and always add default values when data comes from outside your own code.

Frequently Asked Questions

What is destructuring in JavaScript?

Destructuring is a syntax that unpacks values from arrays or objects into individual variables in a single statement. It replaces repetitive lines like const name = user.name with a concise pattern such as const { name } = user.

Does destructuring change the original array or object?

No. Destructuring only copies values out into new variables; the source array or object is left untouched. If you destructure an object that holds another object or array, the extracted variable still points to that same nested reference, but the top-level source is not modified.

Why do I get "Cannot destructure property of undefined"?

You are trying to destructure a value that is null or undefined, which JavaScript does not allow. Guard against it with a fallback, for example const { a } = data || {}, so there is always an object to read from.

What is the difference between array and object destructuring?

Array destructuring uses square brackets and matches by position, so order matters and names are up to you. Object destructuring uses curly braces and matches by key name, so order does not matter but the variable names must match the property names (unless you rename with a colon).

Can I destructure function parameters?

Yes, and it is one of the most useful places to do it. Writing function greet({ name, role = 'student' }) lets the caller pass one options object while your function reads clean, named values, with defaults built in. This pattern is everywhere in React and Node.js.

Do default values work with null?

No. A default value only applies when the property or item is undefined. If the value is null, 0, or an empty string, the default is skipped and the actual value is used. This surprises many beginners when an API returns null for empty fields.