Loading article...
The fill() method changes all elements in an array to a static value, from a start index to an end index.
Array.prototype.customFill = function(value, start = 0, end = this.length) { // Adjust negative indices for start and end start = start < 0 ? Math.max(this.length + start, 0) : start; end = end < 0 ? Math.max(this.length + end, 0) : end; // Fill the array with the given value from start to end (end is exclusive) for (let i = start; i < end; i++) { this[i] = value; } return this; // Return the modified array since fill modifies it in place }; // Example usage: const array1 = [1, 2, 3, 4]; console.log(array1.customFill(0, 2, 4)); // Output: [1, 2, 0, 0] console.log(array1.customFill(5, 1)); // Output: [1, 5, 5, 5] console.log(array1.customFill(6)); // Output: [6, 6, 6, 6]
value: The value to fill the array with.start: The index to begin filling from (defaults to 0).end: The index to stop filling at (non-inclusive, defaults to the arrayβs length).start or end are negative, they are adjusted to count from the end of the array.for loop iterates from start to end (not including end) and fills the array with value..fill() modifies the array directly, customFill returns the modified array..fill()).start = 0 and end = array.length if not provided.Test your understanding with 3 quick questions