Member-only story

The spread (...
) and rest (...
) operators are powerful and versatile tools in JavaScript. While they both use the same syntax, they serve distinct purposes depending on where and how they are applied. In this article, we’ll dive deep into both operators, look at practical use cases, and explore how mastering them can help you write cleaner, more efficient code.
Not a Medium member? Read this article here
1. Understanding the Spread Operator (...
)
The spread operator expands elements from arrays, objects, or iterable items into individual elements. It is commonly used to create copies, merge data, and pass arguments to functions.
1.1 Spread with Arrays
You can use the spread operator to combine arrays or clone them.
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
// Merging two arrays
const mergedArray = [...arr1, ...arr2];
console.log(mergedArray); // [1, 2, 3, 4, 5, 6]
// Cloning an array
const clonedArray = [...arr1];
console.log(clonedArray); // [1, 2, 3]
1.2 Spread with Objects
The spread operator can also clone and merge objects, making it a powerful tool for working with JavaScript objects.
const obj1 = { name: 'Alice', age: 25 };
const obj2 = { job: 'Engineer', location: 'NYC' };
// Merging objects
const mergedObject = { ...obj1, ...obj2 };
console.log(mergedObject);
// { name: 'Alice', age: 25, job: 'Engineer', location: 'NYC' }
// Cloning an object
const clonedObject = { ...obj1 };
console.log(clonedObject); // { name: 'Alice', age: 25 }
1.3 Spread in Function Calls
When working with functions that take multiple arguments, the spread operator can distribute elements from an array as individual parameters.
const numbers = [1, 2, 3];
function sum(a, b, c) {
return a + b + c;
}
console.log(sum(...numbers)); // 6
2. Understanding the Rest Operator (...
)
The rest operator collects multiple elements into a single array or object. It’s often used in function parameters to gather arguments or…