0

I'm using ngx-charts (charts library for Angular2+) and I found this line of code that I don't understand.

@Input() activeEntries: any[] = [];

/* ... */

/* Then, in a function */
this.activeEntries = [...this.activeEntries];

To me, it has no effect. Do you know this usage and what it does ?

Thank you

Valentin Coudert
  • 1,759
  • 3
  • 19
  • 44
  • 2
    Array is an object. Object in JS are assign using reference. So if you directly assign it, both variables will point to same location. `[...this.activeEntries]` This will make a copy. This is same as `array.slice(0)` – Rajesh Nov 24 '17 at 09:39
  • 1
    To create a new array rather than copying a reference. – Arman Charan Nov 24 '17 at 09:39

1 Answers1

1

By spreading the contents of this.activeEntries inside an array literal this code is creating a copy of that array.

It's then assigning a reference to that copy back to this.activeEntries overwriting the original reference held. It is unclear from the context given why that is necessary.

Alnitak
  • 334,560
  • 70
  • 407
  • 495
  • Question: any reason this is preferable to the more direct and clear `Array.from()`? – user949300 Nov 26 '17 at 04:24
  • I expect it's just for consistency - the same library makes a lot of use of `array = [ new_element, ... array ]` as a prepend operation. – Alnitak Nov 26 '17 at 07:50