How to use spread operator in JavaScript
The spread operator provides a concise syntax for expanding arrays, objects, and iterables in various contexts like function calls, array literals, and object merging.
As the creator of CoreUI with extensive JavaScript experience since 2000, I’ve used the spread operator extensively for data manipulation, state updates, and component prop passing.
From my expertise, the most versatile approach is using the three-dot syntax ... to expand elements in arrays, properties in objects, or arguments in functions.
This ES6 feature simplifies common programming patterns while improving code readability and maintainability.
Use the three-dot syntax ... to expand arrays, objects, or iterables in different contexts.
const arr1 = [1, 2, 3]
const arr2 = [4, 5, 6]
const combined = [...arr1, ...arr2]
const obj1 = { a: 1, b: 2 }
const obj2 = { c: 3, d: 4 }
const merged = { ...obj1, ...obj2 }
Here ...arr1 and ...arr2 expand the array elements into the new combined array, creating [1, 2, 3, 4, 5, 6]. For objects, ...obj1 and ...obj2 spread their properties into the merged object, resulting in { a: 1, b: 2, c: 3, d: 4 }. The spread operator creates shallow copies, making it perfect for immutable updates, function argument passing, and avoiding array/object mutation.
Best Practice Note:
This is the same approach we use in CoreUI components for state updates, prop spreading, and data transformation without mutation. The spread operator is essential for functional programming patterns and React state management where immutability is crucial for proper component updates.



