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.