Suggest an editImprove this articleRefine the answer for “Shallow copy of an array”. Your changes go to moderation before they’re published.Approval requiredContentWhat you’re changing🇺🇸EN🇺🇦UAPreviewTitle (EN)Short answer (EN)A **shallow copy** is a new array that has a new reference (changes in it do not affect the original), but nested objects are copied by reference. **Key point:** to make a shallow copy of an array, use `const copy = [...arr]`.Shown above the full answer for quick recall.Answer (EN)Image## What a "shallow copy" is A shallow copy is a **new array** where: - there is a **new reference** (changes in it do not affect the original); - but nested objects are **copied by reference**. --- ## 1. With the spread operator (`...`) - the most modern way ```javascript const arr = [1, 2, 3]; const copy = [...arr]; console.log(copy); // [1, 2, 3] console.log(copy === arr); // false (new array) ``` This way makes a shallow copy - if the elements were objects, they still reference the same data: ```javascript const arr = [{ name: "Tim" }]; const copy = [...arr]; copy[0].name = "Alex"; console.log(arr[0].name); // "Alex" - because the object is shared ``` --- ## 2. With `slice()` and no arguments ```javascript const arr = [1, 2, 3]; const copy = arr.slice(); console.log(copy); // [1, 2, 3] ``` - `slice()` without parameters returns a **new array** - a copy of the whole original. - This is an old but reliable way. --- ## 3. With `Array.from()` ```javascript const arr = [1, 2, 3]; const copy = Array.from(arr); console.log(copy); // [1, 2, 3] ``` Useful if you want not just a copy, but, for example, to apply a transformation to each element: ```javascript const doubled = Array.from(arr, x => x * 2); // [2, 4, 6] ``` --- ## 4. With `concat()` ```javascript const arr = [1, 2, 3]; const copy = [].concat(arr); console.log(copy); // [1, 2, 3] ``` This works because `concat()` returns a new array and does not modify the original. --- ## What is not copied deeply All the listed methods **copy only the top level**. If the array has objects or nested arrays, they **stay by reference**. ```javascript const arr = [[1, 2], [3, 4]]; const copy = [...arr]; copy[0][0] = 99; console.log(arr[0][0]); // 99 - because the nested array is shared ``` --- ## In short: | Way | Code | Creates a new array | Deep copy? | |---|---|---|---| | Spread | `[...arr]` | Yes | No | | `slice()` | `arr.slice()` | Yes | No | | `Array.from()` | `Array.from(arr)` | Yes | No | | `concat()` | `[].concat(arr)` | Yes | No | --- > **Summary:** > To make a shallow copy of an array, use: > > ```javascript > const copy = [...arr]; > ``` > > And if you need **deep copying** (together with nested objects) - > you can use `structuredClone(arr)` or `JSON.parse(JSON.stringify(arr))`.For the reviewerNote to the moderator (optional)Visible only to the moderator. Helps review go faster.