How to clone an array in JavaScript
Cloning arrays is crucial for maintaining immutability, preventing unintended mutations, and implementing state management patterns in modern JavaScript applications. With over 25 years of experience in software development and as the creator of CoreUI, I’ve implemented array cloning countless times in components like form builders, data grids, and state managers where original arrays must remain unchanged. From my extensive expertise, the most modern and efficient solution is using the ES6 spread operator, which creates a shallow copy of the array. This approach is concise, readable, and preserves the original array’s integrity.
Use the spread operator to create a shallow copy of an array.
const original = ['apple', 'banana', 'orange']
const cloned = [...original]
// Result: cloned is a new array with same elements
The spread operator ...
expands all elements from the original array into a new array literal, creating an independent copy. In this example, cloned
becomes a separate array with the same elements as original
. Modifying cloned
won’t affect original
and vice versa. This method works perfectly for arrays containing primitive values (strings, numbers, booleans). For arrays containing objects, this creates a shallow copy, meaning the objects themselves are still referenced, not duplicated.
Best Practice Note:
This is the same approach we use in CoreUI components for state management and preventing prop mutations.
For deep cloning arrays with nested objects, use JSON.parse(JSON.stringify(array))
for simple cases, or consider libraries like Lodash’s cloneDeep()
for complex scenarios. The spread operator remains the best choice for shallow copying.