const array = ["apple"];
const paddedArray = array.fill("pear", 1, 3);
console.log(paddedArray.length);
Logs 1.
The Array.prototype.fill() type mentions:
Changes all array elements from
starttoendindex to a staticvalueand returns the modified array
Why isn’t the modified array being returned?
>Solution :
Array#fill() does return the modified array. It is easy to check:
const array = ["apple"];
const paddedArray = array.fill("pear", 1, 3);
console.log(paddedArray.length); // 1
console.log(array.length); // 1
console.log(array === paddedArray); // literally the same object
What .fill() does not do is invent new indexes. It does not grow the array.
Only values be between the indexes 0 and length-1 are filled. From MDN, the description of the start and end parameters (respectively, second and third parameter) is:
startOptionalZero-based index at which to start filling, converted to an integer.
[…]
- If
start >= array.length, no index is filled.
endOptionalZero-based index at which to end filling, converted to an integer.
fill()fills up to but not including end.[…]
- If
end >= array.lengthorendis omitted,array.lengthis used, causing all indices until the end to be filled.[…]
Then the description reads:
The
fill()method is a mutating method. It does not alter the length ofthis, but it will change the content ofthis.