RangeError: Invalid array length

Quick answer

An array's length must be a non-negative integer under 232-1. You passed new Array(n) or set arr.length = n with an n that's negative, a fraction, NaN, or too large. The fix is almost never at the array itself — it's in whatever calculation produced that number. Trace it back and clamp it: Math.max(0, Math.floor(n)).

The exact error string

new Array(-1);
// Uncaught RangeError: Invalid array length

new Array(3.5);
// Uncaught RangeError: Invalid array length

const arr = [1, 2, 3];
arr.length = -1;
// Uncaught RangeError: Invalid array length

What it actually looks like

Chrome DevTools console showing a red error row reading Uncaught RangeError: Invalid array length, sourced to app.js line 3.
Captured from Chrome 152. new Array(count) where count was -5. The message never prints the offending value, which is the whole difficulty — log the number, not the array, and the bad subtraction shows itself immediately.

Why a single-number Array() argument is special

new Array(a, b, c) with two or more arguments creates an array containing those values — but new Array(n) with exactly one number is special-cased by the spec to mean "create a sparse array with this length", not "an array holding this one number." That's exactly why the number gets validated as a length and can throw. If you actually want a one-element array containing a number, use Array.of(n) or [n] instead — neither has this special case.

new Array(5);        // [ <5 empty items> ] — a sparse array of length 5
Array.of(5);         // [ 5 ] — an array containing the number 5
[5];                 // [ 5 ] — same, more common

Cause 1: a negative length from a bad subtraction

const length = endIndex - startIndex;   // ❌ -3 if startIndex > endIndex
new Array(length).fill(0);
// RangeError: Invalid array length

const length = Math.max(0, endIndex - startIndex);   // ✅ never negative
new Array(length).fill(0);

Cause 2: a non-integer or NaN length

const rows = totalItems / pageSize;   // ❌ 3.4 if it doesn't divide evenly
new Array(rows);
// RangeError: Invalid array length

const rows = Math.ceil(totalItems / pageSize);   // ✅ whole number
new Array(rows);

const count = parseInt(userInput, 10);   // ❌ NaN if userInput isn't numeric
new Array(count);
// RangeError: Invalid array length — NaN is not a valid length either

Cause 3: an unvalidated value from an API or user input

const { itemCount } = await res.json();
new Array(itemCount).fill(null);
// ❌ throws if itemCount is missing, negative, or not actually a number

const safeCount = Number.isInteger(itemCount) && itemCount >= 0 ? itemCount : 0;
new Array(safeCount).fill(null);   // ✅

The exact boundary: what counts as a valid length

An array length must be a whole number between 0 and 232 − 1 inclusive — that is 4,294,967,295, and it is a hard limit in the language, not a memory limit. One past it throws even though the array would never be allocated:

new Array(4294967295).length   // ✅ 4294967295  (2**32 - 1, the maximum)
new Array(4294967296)          // ❌ RangeError: Invalid array length  (2**32)

const a = [1, 2];
a.length = -1;                 // ❌ RangeError — assigning .length validates too
a.length = 1.5;                // ❌ RangeError

That second block matters because the error is not limited to the constructor. Any write to .length goes through the same validation, so a computed truncation such as arr.length = arr.length - n throws the moment n exceeds the current length. Verified on Node v24.15.0 and Chrome 152.

The silent failure that looks like this one

The check applies only when Array() receives exactly one argument and that argument is a number. Change either condition and you get no error at all — and, usually, not the array you wanted:

new Array(5)         // length 5, empty slots        — the "length" reading
new Array(5, 6)      // [5, 6]                       — two args: they're elements
new Array("5")       // ["5"]                        — a STRING, so it's an element
new Array(-1)        // ❌ RangeError

new Array(undefined) // length 1, holding undefined  — no error
new Array(null)      // [null]                       — no error

This is the trap worth knowing about, because it is the mirror image of the error. A count that arrives from JSON.parse(), a query string, or a form field is very often a string: new Array("5") quietly produces a one-element array containing "5", and the bug surfaces hundreds of lines later as a wrong count rather than as a RangeError here. If you are reading a length from anywhere external, coerce it deliberately — and validate it, since Number("abc") is NaN, which does throw. The same class of problem shows up whenever external data is trusted to be the type you expected.

function makeRows(rawCount) {
  const n = Number(rawCount);
  if (!Number.isInteger(n) || n < 0 || n > 2 ** 32 - 1) {
    throw new Error(`bad row count: ${JSON.stringify(rawCount)}`);
  }
  return new Array(n);   // ✅ n is now known-valid
}

Where you actually want "an array holding this one number", Array.of() removes the ambiguity entirely: Array.of(-1) returns [-1] and never inspects its argument as a length.

Common variants at a glance

ValueWhy it's invalidFix
-1negativeMath.max(0, n)
3.5not an integerMath.floor(n) or Math.ceil(n)
NaNnot a number at allvalidate the source before using it
4294967296 or largerexceeds the 232-1 spec limitrethink whether you need an array this large
a single number you meant as a valuenew Array(n) treats it as a length, not contentuse [n] or Array.of(n)

Debugging checklist

Frequently Asked Questions

What does 'Invalid array length' mean?

A JavaScript array's length must be a non-negative integer less than 232 - 1 (4,294,967,295). You passed new Array(n) or set arr.length = n with an n that is negative, a non-integer (like 3.5), NaN, or too large, and the engine rejects it immediately rather than creating a nonsensical array.

Why does new Array(n) behave differently from new Array(a, b, c)?

A single numeric argument to the Array constructor is special-cased to mean "create a sparse array with this length", not "an array containing this one number" — that's exactly why it validates the number as a length. Array.of(n) avoids this special case entirely and always creates a one-element array, whatever n is.

Why is my calculated length negative or NaN?

A subtraction that goes negative (end - start when end < start), a division that produces a fraction, or a value derived from an unvalidated user input or API response are the usual sources. Log the computed length right before using it — the fix is almost always in that upstream calculation, not in the array creation itself.

How large can a JavaScript array actually be?

The theoretical maximum length is 232 - 1 (4,294,967,295), but in practice you'll hit a memory allocation failure or serious performance problems long before that on any real array of actual elements — the length limit is a spec ceiling, not a practical target size.

Does setting arr.length directly have the same restriction?

Yes. arr.length = -1 or arr.length = 3.5 throws the same RangeError as new Array(-1) — both go through the same internal array-length validation. Setting length to a smaller valid number truncates the array; setting it to a larger valid number pads it with empty slots.

How do I prevent this?

Validate or clamp any calculated length before using it: Math.max(0, Math.floor(n)) guarantees a non-negative integer. If the length ultimately comes from user input or an API, treat it the same as any other untrusted number and check it before it reaches an array constructor or length assignment.

References

More JavaScript & runtime errors

Browse the full reference for JavaScript, Node.js, and database errors — exact message, cause, and fix.

All Error References X.map is not a function HTTP Status Codes
About the author

Pasindu Ishan is a Senior Software Engineer working on data streaming systems, which means most days end at a JSON payload that will not parse. The JavaScript references here are checked against a real runtime before being written up. He builds the free in-browser tools at JSON Dev Tools.