Course contentsShow
← JavaScript
Lesson 932 of 2,72321. DestructuringFree lesson

Destructuring with Rest Properties

Capture remaining object properties into a new object using the rest operator.

Destructuring with Rest Properties

What You'll Learn

You'll learn how to collect all "leftover" properties from an object into a brand-new object using the rest operator (...) during destructuring.

The Core Idea

When destructuring an object, you can explicitly pull out specific properties and then capture all the remaining properties into a separate object using the rest syntax. This is incredibly useful when you want to separate a few known properties from everything else.

Think of it like sorting mail: you pull out the urgent letters (specific properties) and put everything else into a "deal with later" pile (the rest object).

How It Works

const user = {
  name: 'Alice',
  age: 30,
  email: 'alice@example.com',
  city: 'Boston',
  country: 'USA'
};

const { name, age, ...otherDetails } = user;

console.log(name);         // 'Alice'
console.log(age);          // 30
console.log(otherDetails); // { email: 'alice@example.com', city: 'Boston', country: 'USA' }

The ...otherDetails collects all properties that weren't explicitly destructured into a new object.

Practical Use Cases

Removing properties:

const data = { id: 1, name: 'Item', price: 50, discount: 10 };
const { discount, ...productInfo } = data;
// productInfo has everything except 'discount'

Function parameters:

function greet({ name, ...rest }) {
  console.log(`Hello, ${name}`);
  console.log('Other info:', rest);
}

greet({ name: 'Bob', age: 25, city: 'NYC' });
// 'Other info:' { age: 25, city: 'NYC' }

Key Takeaway: The rest operator (...) in object destructuring creates a new object containing all properties that weren't explicitly extracted, making it easy to split objects into known and unknown parts.