Looking at some javascript code, I saw (something like) this:
var arr = Array.apply(null, {length: 10});
Reading the MDN documentation for Function.prototype.apply(), I learnt that although it usually expects an array as its second argument which is an array of the arguments to be passed to the invoked function,
you can also use any kind of object which is array-like, so in practice this means it's going to have a property length and integer properties in the range (0...length).
So from what I could tell, it's calling Array() as if it was passed 10 arguments, but since it doesn't define any of those "integer properties", it's as if it was passed 10 undefined arguments. Is that correct?
console.log(arr);
yields
[ undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined ]
Which is totally different to the result of
var barr = new Array(10);
console.log(barr);
which is
[ , , , , , , , , , ]
These arrays also behave differently.
console.log(arr.map(function(item) { return 'hi';}));
console.log(barr.map(function(item) { return 'hi';}));
gives
[ 'hi', 'hi', 'hi', 'hi', 'hi', 'hi', 'hi', 'hi', 'hi', 'hi' ]
[ , , , , , , , , , ]
I wanted to know why the map function didn't work for the second one. So I checked console.log(1 in arr);
which gave true and `console.log(1 in barr);' which gave false.
So my current guess is that arr is an array which contains as integer properties 10 variables which each have the value of undefined and barr is an array which, although it has a length of 10, has no integer properties. And Array.apply works because it asks {length: 10} what its property 0 is, receives undefined, and so assigns undefined to the property 0 of the array it's constructing, and so on. Is my reasoning correct? And is there really no less hackish way to define an array which contains undefined integer properties for each index within its range, rather than having no integer properties at all? Because looking at this, it seems to me that new Array()
is pretty useless.