JS Array.prototype.filter with Array extending class constructor call

Tags: , , ,



I have a Array extending class A which I want to filter. It seems like the constructor gets called another time with just 0 as parameter. Why is that?

Here is an example showing the problem:

class A extends Array {
   constructor(...a){
      console.log(a)
      super(...a);
   }
}

let a = new A("ok", "long");

let b = a.filter((e) => {
   return e.length === 4;
});

console.log(b);

Which logs:

[
    "ok",
    "long"
]
[
    0
]
[
    "long"
]

Where is the 0 comming from?

Answer

Array.prototype.filter is returning a new (array) value. That value needs to be of the same “type” as the original array, i.e. it has to be an instance of your class.

.filter creates a new empty instance of your class:

1. Let O be ? ToObject(this value).
[…]
5. Let A be ? ArraySpeciesCreate(O, 0).
[…]

https://www.ecma-international.org/ecma-262/9.0/index.html#sec-array.prototype.filter

but why would it give me a 0 and not just no paramenter

Because the spec says that the new array is created by calling its constructor with (length) 0 as argument.



Source: stackoverflow