I've noticed that if I do:
Array(n).map(() => console.log('test'))
I get nothing printed.
However if I do:
Array(n).fill().map(() => console.log('test'))
I get test
printed out n
times.
Why is this the case? If I do Array(n).length
I get back n
.
I notice in the REPL that Array(5)
returns:
[ , , , , ]
Whereas Array(5).fill()
returns:
[ undefined, undefined, undefined, undefined, undefined ]
In both cases, typeof
any element in the array === undefined
.
So, what's going on?
I've noticed that if I do:
Array(n).map(() => console.log('test'))
I get nothing printed.
However if I do:
Array(n).fill().map(() => console.log('test'))
I get test
printed out n
times.
Why is this the case? If I do Array(n).length
I get back n
.
I notice in the REPL that Array(5)
returns:
[ , , , , ]
Whereas Array(5).fill()
returns:
[ undefined, undefined, undefined, undefined, undefined ]
In both cases, typeof
any element in the array === undefined
.
So, what's going on?
Share Improve this question edited Apr 24, 2018 at 0:47 Chris Calo 7,8288 gold badges52 silver badges67 bronze badges asked Jan 26, 2016 at 12:22 NRafNRaf 7,54914 gold badges56 silver badges92 bronze badges 03 Answers
Reset to default 27map
only operates on defined integer properties of an array. Array(n)
does not set integer properties, while Array(n).fill()
does. There's a difference between a property that doesn't exist and an extant property whose value is undefined
.
Array(n)
sets the length
property of the array, but it does not set any properties. The array object does not have any integer properties.
.fill
sets all of the integer properties for an array from zero up to one less than length
. When you do Array(n)
you set the length
property of the new aray, and then .fill()
defines and sets each integer property up to n-1
. The array created by Array(n).fill()
does have properties defined up to length - 1
. (The properties happen to be set to undefined
, because you didn't pass an argument to fill
, but they do exist.)
In pracitcal terms, you can see the difference if you do Object.keys(Array(4))
(empty array) versus Object.keys(Array(4).fill())
(a list of strings "0"
to "3"
). In the first case, the properties don't exist; in the second case they do.
Array(n)
creates a new array of size n, the contents have not been defined.
Array(n).fill()
creates an array of size n where every element is set to whatever you passed into fill or undefined in your case since you passed nothing.
Array(n).fill('test')
creates an array of size n filled with 'test'.
I had a requirement to create a scale using a minValue, maxValue, and precision. So, for example, with minValue = 5, maxValue = 7, and precision = 0.5, I should get the array [5, 5.5, 6, 6.5, 7]. I used the following (based off of answers above):
const tickCount = ((maxValue - minValue) / precision) + 1
const ticks = Array(tickCount)
.fill()
.map((x, i) => minValue + i * precision)