Arrays created with new? [duplicate] - javascript

This question already has answers here:
Undefined values in Array(len) initializer
(5 answers)
Closed 7 years ago.
I am confused by the results of mapping over an array created with new:
function returnsFourteen() {
return 14;
}
var a = new Array(4);
> [undefined x 4] in Chrome, [, , , ,] in Firefox
a.map(returnsFourteen);
> [undefined x 4] in Chrome, [, , , ,] in Firefox
var b = [undefined, undefined, undefined, undefined];
> [undefined, undefined, undefined, undefined]
b.map(returnsFourteen);
> [14, 14, 14, 14]
I expected a.map(returnsFourteen) to return [14, 14, 14, 14] (the same as b.map(returnsFourteen), because according to the MDN page on arrays:
If the only argument passed to the Array constructor is an integer
between 0 and 2**32-1 (inclusive), a new JavaScript array is created
with that number of elements.
I interpret that to mean that a should have 4 elements.
What am I missing here?

When you create an array like so:
var arr1 = new Array( 4 );
you get an array that has a length of 4, but that has no elements. That's why map doesn't tranform the array - the array has no elements to be transformed.
On the other hand, if you do:
var arr2 = [ undefined, undefined, undefined, undefined ];
you get and array that also has a length of 4, but that does have 4 elements.
Notice the difference between having no elements, and having elements which values are undefined. Unfortunately, the property accessor expression will evaluate to the undefined value in both cases, so:
arr1[0] // undefined
arr2[0] // undefined
However, there is a way to differentiate these two arrays:
'0' in arr1 // false
'0' in arr2 // true

var a = new Array(4);
This defines a new array object with an explicit length of 4, but no elements.
var b = [undefined, undefined, undefined, undefined];
This defines a new array object with an implicit length of 4, with 4 elements, each with the value undefined.
From the docs:
callback is invoked only for indexes of the array which have assigned
values; it is not invoked for indexes which have been deleted or which
have never been assigned values.
For array a, there are no elements that have been assigned values, so it does nothing.
For array b, there are four elements that have been assigned values (yes, undefined is a value), so it maps all four elements to the number 14.

new Array(len) creates an empty array, and does something different than filling it with undefined values: It sets its length to len. So, it translates to this code:
var newArr = [];
newArr.length = len;
Let's have some fun with newArr (assuming that len = 4):
newArr.length; //4
newArr[1] === undefined; //true
newArr.hasOwnProperty(1); //false
This is because while the is 4 items long, it does not contain any of these 4 items. Imagine an empty bullet-clip: It has space for, say, 20 bullets, but it doesn't contain any of them. They weren't even set to the value undefined, they just are...undefined (which is a bit confusing.)
Now, Array.prototype.map happily walks along your first array, chirping and whistling, and every time it sees an array item, it calls a function on it. But, as it walks along the empty bullet-clip, it sees no bullets. Sure, there are room for bullets, but that doesn't make them exist. In here, there is no value, because the key which maps to that value does not exist.
For the second array, which is filled with undefined values, the value is undefined, and so is the key. There is something inside b[1] or b[3], but that something isn't defined; but Array.prototype.map doesn't care, it'll operate on any value, as long as it has a key.
For further inspection in the spec:
new Array(len) : http://es5.github.com/#x15.4.2.2
Array.prototype.map : http://es5.github.com/#x15.4.4.19 (pay close attention to step 8.b)

One additional answer on the behavior of console.log. Plain simple, the output is sugar and technically wrong.
Lets consider this example:
var foo = new Array(4),
bar = [undefined, undefined, undefined, undefined];
console.log( Object.getOwnPropertyNames(bar) );
console.log( Object.getOwnPropertyNames(foo) );
As we can see in the result, the .getOwnPropertyNames function returns
["length"]
for the foo Array/Object, but
["length", "0", "1", "2", "3"]
for the bar Array/Object.
So, the console.log just fools you on outputting Arrays which just have a defined .length but no real property assignments.

Related

Why is Array(10) != [...Array(10)] [duplicate]

I can use Array() to have an array with a fixed number of undefined entries. For example
Array(2); // [empty × 2]
But if I go and use the map method, say, on my new array, the entries are still undefined:
Array(2).map( () => "foo"); // [empty × 2]
If I copy the array then map does work:
[...Array(2)].map( () => "foo"); // ["foo", "foo"]
Why do I need a copy to use the array?
When you use Array(arrayLength) to create an array, you will have:
a new JavaScript array with its length property set to that number (Note: this implies an array of arrayLength empty slots, not slots with actual undefined values).
The array does not actually contain any values, not even undefined values - it simply has a length property.
When you spread an iterable object with a length property into an array, spread syntax accesses each index and sets the value at that index in the new array. For example:
const arr1 = [];
arr1.length = 4;
// arr1 does not actually have any index properties:
console.log('1' in arr1);
const arr2 = [...arr1];
console.log(arr2);
console.log('2' in arr2);
And .map only maps properties/values for which the property actually exists in the array you're mapping over.
Using the array constructor is confusing. I would suggest using Array.from instead, when creating arrays from scratch - you can pass it an object with a length property, as well as a mapping function:
const arr = Array.from(
{ length: 2 },
() => 'foo'
);
console.log(arr);
The reason is that the array element is unassigned. See here the first paragraph of the description. ... callback is invoked only for indexes of the array which have assigned values, including undefined.
Consider:
var array1 = Array(2);
array1[0] = undefined;
// pass a function to map
const map1 = array1.map(x => x * 2);
console.log(array1);
console.log(map1);
Outputs:
Array [undefined, undefined]
Array [NaN, undefined]
When the array is printed each of its elements are interrogated. The first has been assigned undefined the other is defaulted to undefined.
The mapping operation calls the mapping operation for the first element because it has been defined (through assignment). It does not call the mapping operation for the second argument, and simply passes out undefined.
As pointed out by #CertainPerformance, your array doesn't have any properties besides its length, you can verify that with this line: new Array(1).hasOwnProperty(0), which returns false.
Looking at 15.4.4.19 Array.prototype.map you can see, at 7.3, there's a check whether a key exists in the array.
1..6. [...]
7. Repeat,
while k < len
Let
Pk be ToString(k).
Let
kPresent be the result of calling the [[HasProperty]]
internal method of O with argument Pk.
If
kPresent is true, then
Let
kValue be the result of calling the [[Get]] internal
method of O with argument Pk.
Let
mappedValue be the result of calling the [[Call]] internal
method of callbackfn with T as the this
value and argument list containing kValue, k, and
O.
Call
the [[DefineOwnProperty]] internal method of A with
arguments Pk, Property Descriptor {[[Value]]: mappedValue,
[[Writable]]: true, [[Enumerable]]: true,
[[Configurable]]: true}, and false.
Increase
k by 1.
9. Return A.
As pointed out already, Array(2) will only create an array of two empty slots which cannot be mapped over.
As far as some and every are concerned, Array(2) is indeed an empty array:
Array(2).some(() => 1 > 0); //=> false
Array(2).every(() => 1 < 0); //=> true
However this array of empty slots can somehow be "iterated" on:
[].join(','); //=> ''
Array(2).join(','); //=> ','
JSON.stringify([]) //=> '[]'
JSON.stringify(Array(2)) //=> '[null,null]'
So we can take that knowledge to come up with interesting and somewhat ironic ways to use ES5 array functions on such "empty" arrays.
You've come up with that one yourself:
[...Array(2)].map(foo);
A variation of a suggestion from #charlietfl:
Array(2).fill().map(foo);
Personally I'd recommend this one:
Array.from(Array(2)).map(foo);
A bit old school:
Array.apply(null, Array(2)).map(foo);
This one is quite verbose:
Array(2).join(',').split(',').map(foo);

JS can't map over array created with new Array(100) [duplicate]

I've observed this in Firefox-3.5.7/Firebug-1.5.3 and Firefox-3.6.16/Firebug-1.6.2
When I fire up Firebug:
var x = new Array(3)
console.log(x)
// [undefined, undefined, undefined]
var y = [undefined, undefined, undefined]
console.log(y)
// [undefined, undefined, undefined]
console.log( x.constructor == y.constructor) // true
console.log(
x.map(function() { return 0; })
)
// [undefined, undefined, undefined]
console.log(
y.map(function() { return 0; })
)
// [0, 0, 0]
What's going on here? Is this a bug, or am I misunderstanding how to use new Array(3)?
I had a task that I only knew the length of the array and needed to transform the items.
I wanted to do something like this:
let arr = new Array(10).map((val,idx) => idx);
To quickly create an array like this:
[0,1,2,3,4,5,6,7,8,9]
But it didn't work because:
(see Jonathan Lonowski's answer)
The solution could be to fill up the array items with any value (even with undefined) using Array.prototype.fill()
let arr = new Array(10).fill(undefined).map((val,idx) => idx);
console.log(new Array(10).fill(undefined).map((val, idx) => idx));
Update
Another solution could be:
let arr = Array.apply(null, Array(10)).map((val, idx) => idx);
console.log(Array.apply(null, Array(10)).map((val, idx) => idx));
It appears that the first example
x = new Array(3);
Creates an array with a length of 3 but without any elements, so the indices [0], [1] and [2] is not created.
And the second creates an array with the 3 undefined objects, in this case the indices/properties them self are created but the objects they refer to are undefined.
y = [undefined, undefined, undefined]
// The following is not equivalent to the above, it's the same as new Array(3)
y = [,,,];
As map runs on the list of indices/properties, not on the set length, so if no indices/properties is created, it will not run.
With ES6, you can do [...Array(10)].map((a, b) => a) , quick and easy!
From the MDC page for map:
[...] callback is invoked only for indexes of the array which have assigned value; [...]
[undefined] actually applies the setter on the index(es) so that map will iterate, whereas new Array(1) just initializes the index(es) with a default value of undefined so map skips it.
I believe this is the same for all iteration methods.
ES6 solution:
[...Array(10)]
Doesn't work on typescript (2.3), though
The arrays are different. The difference is that new Array(3) creates an array with a length of three but no properties, while [undefined, undefined, undefined] creates an array with a length of three and three properties called "0", "1" and "2", each with a value of undefined. You can see the difference using the in operator:
"0" in new Array(3); // false
"0" in [undefined, undefined, undefined]; // true
This stems from the slightly confusing fact that if you try to get the value of a non-existent property of any native object in JavaScript, it returns undefined (rather than throwing an error, as happens when you try to refer to a non-existent variable), which is the same as what you get if the property has previously been explictly set to undefined.
For reasons thoroughly explained in other answers, Array(n).map doesn't work. However, in ES2015 Array.from accepts a map function:
let array1 = Array.from(Array(5), (_, i) => i + 1)
console.log('array1', JSON.stringify(array1)) // 1,2,3,4,5
let array2 = Array.from({length: 5}, (_, i) => (i + 1) * 2)
console.log('array2', JSON.stringify(array2)) // 2,4,6,8,10
In ECMAScript 6th edition specification.
new Array(3) only define property length and do not define index properties like {length: 3}. see https://www.ecma-international.org/ecma-262/6.0/index.html#sec-array-len Step 9.
[undefined, undefined, undefined] will define index properties and length property like {0: undefined, 1: undefined, 2: undefined, length: 3}. see https://www.ecma-international.org/ecma-262/6.0/index.html#sec-runtime-semantics-arrayaccumulation ElementList Step 5.
methods map, every, some, forEach, slice, reduce, reduceRight, filter of Array will check the index property by HasProperty internal method, so new Array(3).map(v => 1) will not invoke the callback.
for more detail, see https://www.ecma-international.org/ecma-262/6.0/index.html#sec-array.prototype.map
How to fix?
let a = new Array(3);
a.join('.').split('.').map(v => 1);
let a = new Array(3);
a.fill(1);
let a = new Array(3);
a.fill(undefined).map(v => 1);
let a = new Array(3);
[...a].map(v => 1);
I think the best way to explain this is to look at the way that Chrome handles it.
>>> x = new Array(3)
[]
>>> x.length
3
So what is actually happening is that new Array() is returning an empty array that has a length of 3, but no values. Therefore, when you run x.map on a technically empty array, there is nothing to be set.
Firefox just 'fills in' those empty slots with undefined even though it has no values.
I don't think this is explicitly a bug, just a poor way of representing what is going on. I suppose Chrome's is "more correct" because it shows that there isn't actually anything in the array.
Not a bug. That's how the Array constructor is defined to work.
From MDC:
When you specify a single numeric parameter with the Array constructor, you specify the initial length of the array. The following code creates an array of five elements:
var billingMethod = new Array(5);
The behavior of the Array constructor depends on whether the single parameter is a number.
The .map() method only includes in the iteration elements of the array that have explicitly had values assigned. Even an explicit assignment of undefined will cause a value to be considered eligible for inclusion in the iteration. That seems odd, but it's essentially the difference between an explicit undefined property on an object and a missing property:
var x = { }, y = { z: undefined };
if (x.z === y.z) // true
The object x does not have a property called "z", and the object y does. However, in both cases it appears that the "value" of the property is undefined. In an array, the situation is similar: the value of length does implicitly perform a value assignment to all the elements from zero through length - 1. The .map() function therefore won't do anything (won't call the callback) when called on an array newly constructed with the Array constructor and a numeric argument.
Just ran into this. It sure would be convenient to be able to use Array(n).map.
Array(3) yields roughly {length: 3}
[undefined, undefined, undefined] creates the numbered properties:
{0: undefined, 1: undefined, 2: undefined, length: 3}.
The map() implementation only acts on defined properties.
If you are doing this in order to easily fill up an array with values, can't use fill for browser support reasons and really don't want to do a for-loop, you can also do x = new Array(3).join(".").split(".").map(... which will give you an array of empty strings.
Quite ugly I have to say, but at least the problem and intention are quite clearly communicated.
Since the question is why, this has to do with how JS was designed.
There are 2 main reasons I can think of to explain this behavior:
Performance: Given x = 10000 and new Array(x) it is wise for the constructor to avoid looping from 0 to 10000 to fill the array with undefined values.
Implicitly "undefined": Give a = [undefined, undefined] and b = new Array(2), a[1] and b[1] will both return undefined, but a[8] and b[8] will also return undefined even if they're out of range.
Ultimately, the notation empty x 3 is a shortcut to avoid setting and displaying a long list of undefined values that are undefined anyway because they are not declared explicitly.
Note: Given array a = [0] and a[9] = 9, console.log(a) will return (10) [0, empty x 8, 9], filling the gap automatically by returning the difference between the two values declared explicitly.
Here's a simple utility method as a workaround:
Simple mapFor
function mapFor(toExclusive, callback) {
callback = callback || function(){};
var arr = [];
for (var i = 0; i < toExclusive; i++) {
arr.push(callback(i));
}
return arr;
};
var arr = mapFor(3, function(i){ return i; });
console.log(arr); // [0, 1, 2]
arr = mapFor(3);
console.log(arr); // [undefined, undefined, undefined]
Complete Example
Here's a more complete example (with sanity checks) which also allows specifying an optional starting index:
function mapFor() {
var from, toExclusive, callback;
if (arguments.length == 3) {
from = arguments[0];
toExclusive = arguments[1];
callback = arguments[2];
} else if (arguments.length == 2) {
if (typeof arguments[1] === 'function') {
from = 0;
toExclusive = arguments[0];
callback = arguments[1];
} else {
from = arguments[0];
toExclusive = arguments[1];
}
} else if (arguments.length == 1) {
from = 0;
toExclusive = arguments[0];
}
callback = callback || function () {};
var arr = [];
for (; from < toExclusive; from++) {
arr.push(callback(from));
}
return arr;
}
var arr = mapFor(1, 3, function (i) { return i; });
console.log(arr); // [1, 2]
arr = mapFor(1, 3);
console.log(arr); // [undefined, undefined]
arr = mapFor(3);
console.log(arr); // [undefined, undefined, undefined]
Counting Down
Manipulating the index passed to the callback allows counting backwards:
var count = 3;
var arr = arrayUtil.mapFor(count, function (i) {
return count - 1 - i;
});
// arr = [2, 1, 0]

How [undefined, undefined, undefined] and new Array(3) are different in JavaScript? [duplicate]

This question already has answers here:
Undefined values in Array(len) initializer
(5 answers)
Closed 5 years ago.
Suppose we have 3 arrays:
var arr1 = [undefined, undefined, undefined];
var arr2 = [, , ,];
var arr3 = new Array(3);
Are all of them identical in JavaScript?
If we wants to use undefined as default value for fixed size array, can we use them interchangeably?
The second two are the same (though the second one might cause issues on some browsers), but the first is different.
The first one
var arr1 = [undefined, undefined, undefined];
makes explicit assignments to the first three indexes in the array. Even though you're assigning undefined, the fact that indexes 0, 1, and 2 are targets of assignment operations means that those elements of the array will be treated as "real" by methods like .reduce():
[undefined, undefined, undefined].reduce(function(c) { return c + 1; }, 0);
// 3
[,,].reduce(function(c) { return c + 1; }, 0);
// 0
Many of the Array.prototype methods skip uninitialized array elements.

Sparse arrays and reduce in JavaScript

One would think that in JavaScript:
var array = [1,2,undefined,4];
is the same as:
var array = [1,2];
array.length = 3;
array.push(4);
but it's not. This code shows it:
var array1 = [1,2];
array1.length = 3;
array1.push(4);
var array2 = [1,2,undefined,4];
traverseArray(array1);
traverseArray(array2);
function traverseArray(array) {
console.log("trying: " + array);
console.log("reduce:");
array.reduce(function(prev, current, index, array) {
if(current === undefined) {
console.log("Found undefined");
}
console.log(index+": " +current);
}, undefined);
console.log("for loop:")
for(var i=0;i < array.length;i++) {
var current = array[i];
console.log(i+": " +current);
}
console.log();
}
Output:
trying: 1,2,,4
reduce:
0: 1
1: 2
3: 4
for loop:
0: 1
1: 2
2: undefined
3: 4
trying: 1,2,,4
reduce:
0: 1
1: 2
Found undefined
2: undefined
3: 4
for loop:
0: 1
1: 2
2: undefined
3: 4
Why is undefined in array1 not the same as undefined in array2 and why does the for loop act the same but reduce does not?
array1 has three numerically-named properties: 0, 1, and 3.
array2 has four numerically-named properties: 0, 1, 2, and 3. The value of the property named 2 happens to be undefined.
When you ask an object for the value of a property it doesn't have, the result is undefined.
In the for loop, you ask each array for the values of its properties named 0, 1, 2, and 3. For array1, the property named 2 does not exist, so the property access produces undefined. For array2, the property does exist, but its value actually is undefined, so you get the same result.
On the other hand, reduce only operates on properties that actually exist. From the ECMAScript specification, this is how reduce loops over arrays, using a counter k:
Repeat, while k < len
Let Pk be ToString(k).
Let kPresent be the result of calling the [[HasProperty]] internal method of O with argument Pk.
If kPresent is true, then... [use the value at index k for the reduce call]
So, we can see that an index is only used if passes a [[HasProperty]] check. array1 does not have a property named 2, so that index is skipped.
apsillers nailed it in the comments . . . the difference is that in array2 you have actually assigned an undefined value to the 3rd element in the array (i.e., at index 2), where as, in array1, you have two elements initially, change the length property, and then add a third element in the forth position.
Here are the relevent sections from MDN that explains why the distinction is important:
From the page on Array.length:
When you extend an array by changing its length property, the number of actual elements does not increase; for example, if you set length to 3 when it is currently 2, the array still contains only 2 elements. Thus, the length property says nothing about the number of defined values in the array.
From the page on Array.push():
The push method relies on a length property to determine where to start inserting the given values.
The key here, is really that the length property is really, simple a property that is in no way inherantly tied to the contents of the array. It is simply because the various methods of Array also happen to maintain that property, as they "do their work", that I behaves as if it is.
So, as a result, in array2, the code is actually reporting back the undefined value that you assigned to array2[2], whereas, with array1, the code is interpreting the absence of a value at array1[2] as undefined.

Chaining the map function to the Array Constructor [duplicate]

This question already has answers here:
(new Array(10)).map(function() { return 1;}) returns [, , , , , ...] ... Why? [duplicate]
(3 answers)
Closed 7 years ago.
Trying to find a way to inline the creation of an array of data given its size, i tried
var n = 4;
var data = (new Array(n)).map(function(x) { return 1 });
which gave me
[undefined, undefined, undefined, undefined]
Regarding that
new Array(n)
gives
[undefined, undefined, undefined, undefined]
and that
[undefined, undefined, undefined, undefined].map(function(x) { return 1 });
returns
[1, 1, 1, 1]
I would expect to be able to chain the Array constructor and the map function.
Any insights on that behavior ?
new Array(n) creates an array of size n, but with no elements in it. This is called a sparse array. Though there are no elements in the array, the browser represents them as undefined. And Array.prototype.map will ignore the array elements which are not defined yet.
Quoting from the ECMA 5.1 Specification for Array.prototype.map,
callbackfn is called only for elements of the array which actually exist; it is not called for missing elements of the array.
To be able to chain the map function, you might want to do like this
console.log(Array.apply(null, {length: n}).map(function(x) { return 1 }));
# [ 1, 1, 1, 1 ]

Categories