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?
JavaScript Array fill() The fill() method fills specified elements in an array with a value. The fill() method overwrites the original array. Start and end position can be specified. If not, all elements will be filled.
In JavaScript, you can use the Array. fill() method to populate an array with a zero or any other value like an object or a string. This method replaces all elements in an array with the value you want to populate the array with and returns the modified array.
Using push() method: We use the push() method to fill static values in an array in JavaScript. We use the push() method inside the for() loop. The push() method always adds a new element to the end of the array so that means the push() method cannot replace the elements of the array.
map
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'.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With