2

Can someone explain to me the difference between assigning an array directly, using spread operator and the slice method in JavaScript? For instance:

const a = [1,2,3,4,5];
const b = a;
const c = a.slice();
const d = [...a];

What is the difference between b, c and d arrays ? Has it got something to do with shallow and deep copies?

Andy
  • 61,948
  • 13
  • 68
  • 95
coolest-duck
  • 105
  • 1
  • 1
  • 10
  • 2
    `a.slice()` and `[...a]` produce shallow copies. `const b = a;` makes `b` point to the same array as `a`. – Unmitigated Apr 01 '23 at 06:12
  • 1
    Also spread works on any iterable (plus objects), while slice is on Array.prototype (so only works on arrays); and using spread to copy a sparse array will result in undefined elements (rather than empty elements). None of those give you a deep copy, for that you could use `structuredClone`, `JSON.parse(JSON.stringify(x))`, or some other option. – Zac Anger Apr 01 '23 at 06:16
  • @Unmitigated, the official documentation of shallow copy says that "A shallow copy of an object is a copy whose properties share the same references (point to the same underlying values) as those of the source object. As a result, when you change either the source or the copy, you may also cause the other object to change too — and so, you may end up causing changes to the source or copy that you don't expect. That behavior contrasts with the behavior of a deep copy, in which the source and copy are completely independent." Doesn't this imply that both arrays c, d are like b (in ref)? – coolest-duck Apr 01 '23 at 06:22
  • If you add elements to `a`, it affects `b` but not `c` or `d`. – Unmitigated Apr 01 '23 at 06:24

1 Answers1

0

With slice() you can copy a portion of an array.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice

Tania
  • 1
  • 1