Skip to content

RangeError: Invalid repeat count

Quick summary

You passed a negative number, Infinity, or a huge count to .repeat — the result cannot be a valid string.

Why this happens

  • Count is negative (e.g., -1) which is meaningless for repetition

  • Count is Infinity or a number that overflows the max string length

  • Count comes from user input or a calculation that was not validated

Minimal example

✗ Broken code
const line = '-'.repeat(-5); // RangeError: Invalid count value
console.log(line);
✓ Fixed code
const count = Math.max(0, -5);
const line = '-'.repeat(count); // ''
console.log(line);

A negative count has no meaning for repetition, so .repeat throws. Clamping to 0 produces an empty string instead of crashing.

How to diagnose

  • Read the RangeError: 'Invalid count value'

  • Log the count value right before the .repeat call

  • Check whether the count can be negative or very large

How to fix

  • Clamp the count to a non-negative integer: Math.max(0, Math.floor(count))

  • Validate user input before passing it to .repeat

  • Guard against Infinity with Number.isFinite

How to prevent

  • Always validate repeat counts before calling .repeat

  • Cap counts at a reasonable maximum for your use case

Related Resources

Related Glossary

Related Lessons

← Back to language