Uncaught RangeError: Invalid array length JavaScript

The issue

This issue can happen for any invalid array length. In our case we were setting the array length to a negative number. As the negative number for array length is not valid, it throws the error message.

The reason

The code we tried were similar to the following:

let booklist = [];
booklist.length = booklist.length - 1; 
// Uncaught RangeError: Invalid array length

The solution

We solved it using a condition before the statement like below:

let booklist = [];
if(booklist.length > 0)
booklist.length = booklist.length - 1; 
// Uncaught RangeError: Invalid array length
Share