Developed By
Gautam Kumar - Full stack developer
DEEP DIVE INTO
The fill()
method is a built-in method for arrays in JavaScript. It is used to fill all or a portion of an array with a specific value. In this deep dive, we'll explore the fill()
method in detail, including its usage, behavior, and some important considerations.
javascriptarray.fill(value, start, end);
array: The array you want to modify.
value: The value with which you want to fill the array.
start (optional): The index at which filling starts. If not provided, it starts at index 0.
end (optional): The index at which filling ends (exclusive). If not provided, it fills until the end of the array.
The fill() method modifies the original array in place and returns the modified array.
Filling an Entire Array:
javascriptconst numbers = [1, 2, 3, 4, 5];
numbers.fill(0);
console.log(numbers); // Outputs: [0, 0, 0, 0, 0]
In this example, the fill()
method is used to fill the entire numbers array with the value 0.
Filling a Portion of an Array:
javascriptconst colors = ['red', 'green', 'blue', 'yellow'];
colors.fill('white', 1, 3);
console.log(colors); // Outputs: ['red', 'white', 'white', 'yellow']
Here, the fill()
method is used to fill a portion of the colors array, starting at index 1 (inclusive) and ending at index 3 (exclusive), with the value 'white'.
Using Negative Indices:
javascriptconst array = [1, 2, 3, 4, 5];
array.fill(0, -2, -1);
console.log(array); // Outputs: [1, 2, 3, 0, 5]
In this example, negative indices are used to fill a portion of the array from the second-to-last element to the last element with the value 0.
The fill()
method modifies the original array in place. Be cautious about unintended side effects when using it.
If you need to create a new array with the same value repeated, you can use array constructors or other methods like Array.from()
:
javascriptconst newArray = new Array(5).fill('default'); // Creates a new array with 5 elements, each filled with 'default'.
The fill()
method can be useful for initializing arrays or resetting their values. For example, you can use it to clear an array by filling it with a default value.
javascriptlet scores = [90, 88, 75, 94];
scores = scores.fill(0);
console.log(scores); // Outputs: [0, 0, 0, 0]
In this example, the fill() method is used to reset all scores to 0.
The fill()
method has a time complexity of O(N), where N is the number of elements in the filled portion of the array. This means that it runs in linear time, which is generally efficient.
In summary, the fill()
method is a convenient array method for initializing, resetting, or modifying portions of an array with specific values.
It directly modifies the original array, so use it with care to avoid unintended side effects.
warning