Search code examples
javascriptarraysparameters

JavaScript Array.prototype.fill: meaning of parameters


The documentation on MDN indicates that the syntax for Array.prototype.fill is:

Array.prototype.fill(value[, start[, end]])

The example

console.log([1, 2, 3].fill(4, 1, 1));         // [1, 2, 3]

in the documentation and my testing agrees with the commented answer.

However, I can’t see how that can be right. The parameters indicate that indexes 1 through 1 should be filled with 4. Index 1 has the value of 2, so I should have though that the result should be [1,4,3].

What is the correct interpretation of the parameters start and end?


Solution

  • console.log([1, 2, 3].fill(4, 1, 1));
    

    First argument 4 is value to fill with. Second argument 1 is starting index (where to start from). Third argument 1 is ending index which is exclusive.

    So if you do: console.log([1, 2, 3].fill(4, 0, 3));

    It will start filling [1,2,3] array starting from index 0 (value 1) and overwriting all values up to the index of 2 since we said 3 is exclusive.

    So result will be: [4, 4, 4]