How to fix: "IndexOutOfBoundsException: Invalid index"

IndexOutOfBoundsException: Invalid index is thrown when an invalid index is used. This can happen when the array index is out of range or when the array is not allocated.

The following examples show how to create and use an array.

The following example creates an array of five elements and prints the values stored in the array.

var myArray = [];

myArray[0] = 1;
myArray[1] = 2;
myArray[2] = 3;
myArray[3] = 4;
myArray[4] = 5;

console.log(myArray);

The following example creates an array of five elements, but attempts to access the sixth element, which causes an IndexOutOfBoundsException.

var myArray = [];

myArray[0] = 1;
myArray[1] = 2;
myArray[2] = 3;
myArray[3] = 4;
myArray[4] = 5;

console.log(myArray[6]); // Throws IndexOutOfBoundsException

IndexOutOfBoundsException can also occur when the array is not allocated. The following example creates an uninitialized array and then tries to access the fifth element, which causes an IndexOutOfBoundsException.

var myArray = [];

console.log(myArray[5]); // Throws IndexOutOfBoundsException

IndexOutOfBoundsException has a history dating back to at least the early 1990s. The first recorded mention of the exception is in a Usenet post from 1993. The exception was originally called ArrayIndexOutOfBoundsException.

There are several ways to fix an IndexOutOfBoundsException. One way is to check the array index before accessing the array element. The following example checks the array index before accessing the array element and avoids the IndexOutOfBoundsException.

var myArray = [];

myArray[0] = 1;
myArray[1] = 2;
myArray[2] = 3;
myArray[3] = 4;
myArray[4] = 5;

console.log(myArray[5]); // No exception thrown

Another way to fix an IndexOutOfBoundsException is to increase the size of the array. The following example increases the size of the array to six elements and then prints the values stored in the array.

var myArray = [];

myArray[0] = 1;
myArray[1] = 2;
myArray[2] = 3;
myArray[3] = 4;
myArray[4] = 5;

myArray[5] = 6;

console.log(myArray);
💡
Need a writer? Want to work with me? I have a subscription copywriting service available at Zipply.io. Subscribe to a set number of words and split it into as many copy assets as you need. Scale your startup, small business, or MVP. Upgrade, downgrade and pause at any time. Start your subscription here.