Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is array.fill() not returning the modified array?

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 start to end index to a static value and returns the modified array

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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:

start Optional

Zero-based index at which to start filling, converted to an integer.

[…]

  • If start >= array.length, no index is filled.

end Optional

Zero-based index at which to end filling, converted to an integer. fill() fills up to but not including end.

[…]

  • If end >= array.length or end is omitted, array.length is 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 of this, but it will change the content of this.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading