To initialize a JavaScript array with a fixed length and default values, create an array of length n with new Array(n) or Array.from({ length: n }, ...) and populate it using .fill(value) for primitives or a mapper callback inside Array.from() (or Array.from({ length: n }, () => value)) for objects, arrays, or computed values. Passing an object or array reference directly into .fill() shares that same reference across every slot, so a factory function is essential for mutable defaults.
1. Initializing with Primitive Default Values (new Array(n).fill(...))
When default values are immutable primitives—such as 0, false, "", or null—combining new Array(length) with .fill(defaultValue) is concise and fast:
// Create a fixed-length array filled with a primitive default value
function createFilledArray(length, defaultValue) {
if (!Number.isInteger(length) || length < 0) {
throw new RangeError("Expected length to be a non-negative integer.");
}
return new Array(length).fill(defaultValue);
}
// Example usage:
const zeros = createFilledArray(5, 0);
const flags = createFilledArray(3, false);
console.log(zeros); // [0, 0, 0, 0, 0]
console.log(flags); // [false, false, false]
- Validates length safely: Checking
Number.isInteger(length) && length >= 0preventsRangeErroron negative, non-integer, orNaNlengths. - Dense resulting array:
.fill()writes values to every index from0tolength - 1, avoiding the sparse “holes” created bynew Array(length)alone.
2. Initializing with Fresh Objects, Arrays, or Computed Values (Array.from)
When each slot needs its own independent object, nested array, or index-based value, pass a mapping function as the second argument to Array.from({ length }, mapFn):
// Create an array of fixed length where each item is freshly generated
function createMappedArray(length, factoryFn) {
if (!Number.isInteger(length) || length < 0) {
throw new RangeError("Expected length to be a non-negative integer.");
}
if (typeof factoryFn !== "function") {
throw new TypeError("Expected factoryFn to be a function.");
}
return Array.from({ length }, (_, index) => factoryFn(index));
}
// Example usage:
const gridRows = createMappedArray(3, () => new Array(4).fill(0));
const numberedItems = createMappedArray(4, (i) => ({ id: i + 1, active: false }));
gridRows[0][1] = 9;
console.log(gridRows[1][1]); // 0 (independent row)
console.log(numberedItems); // [{ id: 1, active: false }, ...]
- Avoids shared-reference bugs: Unlike
new Array(3).fill([]), calling() => []per slot ensures mutating one row or object does not mutate all others. - Index-aware initialization: The second callback argument (
index) makes sequential IDs, coordinates, or pattern values straightforward.
3. Why new Array(n) Alone Behaves Differently
Calling new Array(n) creates an array with length === n but empty slots (sparse holes), which many array methods skip over:
// Sparse slots vs. initialized elements
const sparse = new Array(3);
const dense = Array.from({ length: 3 }, () => "init");
console.log(sparse.map((x) => x ?? "empty")); // [empty x 3] (callback skipped)
console.log(dense.map((x) => x)); // ["init", "init", "init"]
- Skip sparse traps: Methods like
.map()and.forEach()ignore uninitialized slots innew Array(n). - Single-argument pitfall:
new Array(3)sets length to3, whereasnew Array("3")creates a one-element array["3"].
TL;DR: Use new Array(length).fill(primitive) for primitive defaults, and Array.from({ length }, (_, index) => ...) whenever each element needs a fresh object, nested array, or index-derived value.
