How to use the JavaScript spread operator effectively

Full stack engineer but passionnated by front-end Angular Expert / NX / JavaScript / Node / Redux State management / Rxjs
Search for a command to run...

Full stack engineer but passionnated by front-end Angular Expert / NX / JavaScript / Node / Redux State management / Rxjs
No comments yet. Be the first to comment.
In last article I explained how to use variables in JavaScript but I also mentioned undefined, here I will try my best to explain to you what is undefined, what is the difference with null, why both are existing and I will give you some examples. und...
A structured approach to Angular applications with Ngrx Signal Store

The useEffect hook is fundamental to React functional components, but its behaviour changes dramatically based on how you handle the dependencies array. Let's explore the three main patterns and when to use each one. useEffect without dependencies ar...

Git worktree is a Git feature that allows you to check out multiple branches at once in different directories, without cloning the repository again. This powerful capability transforms how developers handle parallel development workflows. The Problem...

When working with Git in collaborative environments, you'll inevitably encounter situations where you need to overwrite remote history. Two commands come into play: git push --force and git push --force-with-lease. Understanding the difference betwee...

Ever needed to create a union type from an array of objects in TypeScript? There's an elegant solution using the [number] index signature notation that can save you from maintaining duplicate type definitions. The Problem Let's say you have an array ...
![TypeScript's [number] Index Signature: Extract Union Types from Arrays](/_next/image?url=https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1752960594694%2Fe2be9492-869f-4169-bb1a-950ee81a3887.png&w=3840&q=75)
The spread operator (...) is one of the most useful features in modern JavaScript. It allows you to expand arrays, objects, and other iterable elements in places where multiple elements are expected. This article will explain how to use the spread operator effectively.
The spread operator uses three dots (...) before a variable name. It "spreads" or expands the contents of arrays, objects, or strings into individual elements.
console.log([π,π,π]); // Output: [π,π,π]
// With spread operator
console.log(...[π,π,π]); // Output: π π π
You can create a shallow copy of an array
const originalArray = [π,π,π];
const copiedArray = [...originalArray];
console.log(copiedArray); // [π,π,π]
You can merge multiple arrays easily
const fruits = [π, π];
const vegetables = [π₯, π ];
const food = [...fruits, ...vegetables];
console.log(food); // [π, π, π₯, π ]
You can insert new elements while keeping existing ones
const healthyFood = [π, π, π₯, π ];
const moreHealthyFood = [π, ...healthyFood, π₯¦, π₯];
console.log(moreHealthyFood); // [π, π, π, π₯, π , π₯¦, π₯]
You can create a shallow copy of an object
const person = { name: 'Gilles', age: 29 };
const personCopy = { ...person };
console.log(personCopy); // { name: 'Gilles', age: 29 }
You can combine multiple objects into one
const person = { name: 'Gilles', age: 29 };
const contactInfo = { email: 'gilles@email.com', phone: '123-456-7890' };
const fullProfile = { ...person, ...contactInfo };
console.log(fullProfile);
// { name: 'Gilles', age: 29, email: 'gilles@email.com', phone: '123-456-7890' }
You can override specific properties of an object while keeping others
const person = { name: 'Gilles', age: 29, city: 'Toulouse' };
const updatedPerson = { ...person, age: 29, country: 'France' };
console.log(updatedPerson);
// { name: 'Gilles', age: 29, city: 'Toulouse', country: 'France' }
You can pass array elements as separate arguments to functions:
function addThreeNumbers(a, b, c) {
return a + b + c;
}
const numbers = [5, 10, 15];
const result = addThreeNumbers(...numbers);
console.log(result); // 30
You can spread a string into individual characters:
const word = 'hello';
const letters = [...word];
console.log(letters); // ['h', 'e', 'l', 'l', 'o']
The spread operator creates shallow copies, not deep copies. This means nested objects or arrays are still referenced:
const original = {
name: 'Gilles',
hobbies: ['reading', 'coding']
};
const copy = { ...original };
copy.hobbies.push('cycling');
console.log(original.hobbies); // ['reading', 'coding', 'cycling']
// The original object is affected!
When merging objects, properties from later objects override earlier ones:
const obj1 = { a: 1, b: 2 };
const obj2 = { b: 3, c: 4 };
const merged = { ...obj1, ...obj2 };
console.log(merged); // { a: 1, b: 3, c: 4 }
// obj2.b overrides obj1.b
While the spread operator creates shallow copies, you can achieve deep copying by combining it with other techniques:
// For simple nested objects (no functions, dates, etc.)
const original = {
name: 'Gilles',
address: { city: 'Toulouse', country: 'France' },
hobbies: ['reading', 'coding']
};
const deepCopy = {
...original,
address: { ...original.address },
hobbies: [...original.hobbies]
};
// Now changes to deepCopy won't affect original
deepCopy.address.city = 'MontrΓ©al';
deepCopy.hobbies.push('cycling');
console.log(original.address.city); // 'Toulouse' (unchanged)
console.log(original.hobbies); // ['reading', 'coding'] (unchanged)
The spread operator is essential in React for:
State updates: Change one property in a state object while keeping others unchanged
Props passing: Send multiple properties to child components at once
Array state management: Add or remove items from lists without mutating the original array
Event handling: Create new objects when updating form data
Component composition: Combine default props with custom props
In Angular, the spread operator helps with:
Data binding: Update component properties while preserving existing data
Array manipulation: Add, remove, or modify items in lists for templates
Form handling: Create updated objects when processing form submissions
API responses: Merge server data with local component state
Template data: Combine multiple data sources for display
Both frameworks benefit from the spread operator because it helps create new objects and arrays instead of modifying existing ones, which prevents unexpected bugs and makes applications more predictable.
The spread operator is a powerful tool that makes JavaScript code cleaner and more readable. It simplifies many common tasks like copying arrays, merging objects, and passing arguments to functions. With careful use, you can even achieve deep copying without external libraries.
Practice using the spread operator in your projects to become more comfortable with this essential JavaScript feature. Start with simple cases and gradually work your way up to more complex scenarios.