Code Logo

Initialize with Array.fill()

Published at25 Jul 2026
JavaScript Data Structures Easy 1 views
Like0

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

Example 1
Input
4,true
Output
[true,true,true,true]
Explanation

Array of booleans

Example 2
Input
5,1
Output
[1,1,1,1,1]
Explanation

Array of 5 ones

Example 3
Input
3,0
Output
[0,0,0]
Explanation

Array of 3 zeros

Example 4
Input
1,42
Output
[42]
Explanation

Single element

Example 5
Input
2,null
Output
[null,null]
Explanation

Array of nulls

Algorithm Flow

Recommendation Algorithm Flow for Initialize with Array.fill()

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.

function solution(arr, v) {
  return arr.fill(v);
}

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

javascript - Approach 1
function solution(n, val) {
  return new Array(n).fill(val);
}