How to create a copy of an array in JavaScript, not a reference to it?
Hello everyone! I'm a beginner in JavaScript and I've encountered a problem that I can't solve. When I try to copy an array, changes to the new array affect the original. Here's an example:
```javascript
let original = [1, 2, 3];
let copy = original;
copy.push(4);
console.log(original); // [1, 2, 3, 4] — I don't want original to change!
```
I understand that `copy = original` creates not a copy, but a reference to the same array. But how do I make `copy` completely independent? I tried `copy = original.slice()`, and it worked for simple numbers. But when I have nested arrays or objects, changes still affect the original:
```javascript
let nested = [[1, 2], [3, 4]];
let copyNested = nested.slice();
copyNested[0].push(5);
console.log(nested[0]); // [1, 2, 5]
No answers yet.
Log in to leave an answer