Code Logo

Initialize with Array.fill()

Published at25 Jul 2026
JavaScript Data Structures Easy 0 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()
Recommendation Algorithm Flow for Initialize with Array.fill()

Solution Approach

function solution(n, val) {
  return new Array(n).fill(val);
}

Best Answers

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