I have the array var john = ['asas','gggg','ggg'];
If I access john
at index 3, ie. john[3]
, it fails.
How can I display a message or alert saying that there is no value at that index?
JavaScript arrays don't really have a concept of size. You can try to retrieve an element from any position in the array, and if no element exists it will return undefined . There is no such thing as an out of bounds error.
To avoid this condition, you can write an exception handler that processes the exception and keeps your program running. Place the code that cause the exception in the try block. If there is an exception in the try block, transfer the control to the catch block. If there is no catch block the program will terminate.
If we use an array index that is out of bounds, then the compiler will probably compile and even run. But, there is no guarantee to get the correct result. Result may unpredictable and it will start causing many problems that will be hard to find. Therefore, you must be careful while using array indexing.
The ArrayIndexOutOfBoundsException is one of the most common errors in Java. It occurs when a program attempts to access an invalid index in an array i.e. an index that is less than 0, or equal to or greater than the length of the array.
function checkIndex(arrayVal, index){
if(arrayVal[index] == undefined){
alert('index '+index+' is undefined!');
return false;
}
return true;
}
//use it like so:
if(checkIndex(john, 3)) {/*index exists and do something with it*/}
else {/*index DOES NOT EXIST*/}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With