What is Object Rest Spread in JavaScript: Simple Explanation and Examples
object rest and spread are syntax features that let you extract or combine properties from objects easily. The rest syntax collects remaining properties into a new object, while the spread syntax copies properties from one object into another.How It Works
Imagine you have a box full of items (an object with properties). Sometimes, you want to take out a few specific items and keep the rest together in another box. The rest syntax lets you do exactly that by collecting all leftover properties into a new object.
On the other hand, the spread syntax is like taking items from one box and spreading them out into another box, copying all properties easily. This helps when you want to combine objects or add new properties without changing the original.
Example
This example shows how to use object rest to separate some properties and keep the rest, and how to use spread to combine objects.
const person = { name: 'Alice', age: 30, city: 'Paris', job: 'Developer' }; // Using rest to extract 'name' and keep the rest const { name, ...details } = person; // Using spread to create a new object with extra property const updatedPerson = { ...person, country: 'France' }; console.log(name); // Alice console.log(details); // { age: 30, city: 'Paris', job: 'Developer' } console.log(updatedPerson); // { name: 'Alice', age: 30, city: 'Paris', job: 'Developer', country: 'France' }
When to Use
Use object rest when you want to pick out some properties from an object but keep the rest grouped together. This is helpful in functions that receive many options but only need a few directly.
Use object spread when you want to create a new object by copying properties from existing ones, especially to add or override some properties without changing the original object. This is common in state updates in frameworks like React.
Key Points
- Rest syntax collects remaining properties into a new object.
- Spread syntax copies properties from one object to another.
- Both help write cleaner and more readable code when working with objects.
- They do not mutate the original objects, promoting safer code.