Initialize with Array.fill()
Write a JavaScript function that takes a length n and a value, and returns an array of length n with all elements set to the given value using Array.fill(). The fill() method changes all elements in an array to a static value from a start index to an end index.
Array.prototype.fill() is a JavaScript method introduced in ES6 that fills an array with a specified value. It mutates the original array and returns the modified array. When called on an array created with new Array(n), fill() initializes all positions. Without fill(), new Array(n) creates an array with empty slots that won't work with map().
The fill() method is the standard way to create pre-initialized arrays in JavaScript. The pattern new Array(n).fill(value) creates an array of length n where every element is value. This is essential for creating arrays for use with map(), filter(), and reduce(). Much simpler than manual loops.
Time complexity is O(n) where n is the array length. Space complexity is O(n) for the array. When filling with objects, all elements reference the same object (fill does not deep clone).
Edge cases include zero-length arrays (returns empty array), filling with undefined, null, or complex values, and understanding that fill with an object creates shared references rather than independent copies.
Example Input & Output
Array of booleans
Array of 5 ones
Array of 3 zeros
Single element
Array of nulls
Algorithm Flow
Solution Approach
Set all elements of an array to a static value using fill(). This method modifies the original array in place and also returns the modified array. Optional start and end indices limit which portion gets filled.
fill() mutates the original array. To create a new array of repeated values: Array(n).fill(v). When filling with objects, be aware that all elements reference the same object instance, not separate copies.
Time complexity is O(n), space complexity is O(1).
Best Answers
function solution(n, val) {
return new Array(n).fill(val);
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
