Why is this javascript Array() producing an array with only one element? [closed]

As per Sebastian’s comment: your requestCount is almost certainly a string instead of a number:

new Array(4).fill()
// Array(4) [ undefined, undefined, undefined, undefined ]

new Array("4").fill()
// Array(1) [ undefined ]

In fact the second constructor does something wildly different from the first one. new Array(int) will create an Array with <int> empty slots. However, new Array(not-an-int) will create an array with the constructor arguments as content, so:

new Array(4)
// Array(4) [ <4 empty slots> ]

new Array("4")
// Array(1) ["4"]

So if we call .fill() without any argument, we’re saying “replace the content for all elements with undefined“, and we have an array containing a single element (the string “4”), then we end up with [undefined].

The lesson here is to always validate your inputs before you pass them to functions/constructors that are polymorphic with respect to argument type:

const requestCount = await campaign.methods.getRequestsCount().call();

// I don't know what that line can return, so verify that there even
// _is_ a result. If there is, then we can continue:

const n = parseInt(requestCount);

if (isNaN(n)) {
  // this is a probably something you should have a contingency for
}

// and if n _is_ a number, it also needs to make sense as an array length value
else if (n > 0) {
  const mapped = [...Array(n)].map((_,i) => {
    // do something with i
  });
}

But that “convenient syntax” using map basically wastes time on creating an array that we’re then immediately throwing away. That’s silly: we can achieve the exact same result without immediately invoking garbage collection by using array’s stack functions:

// note: let, not const, because we're going to run it down to 0
let n = .....

...code that returns early based on bad values of n...

const mapped = [];
while(n--) {
  // since we're running our index backwards, we use unshift(),
  // which is like push() but for the start, not end, of an array.
  mapped.unshift(campaign.methods.requests(n).call());
}

Leave a Comment