Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I log an ArrayIndex out of bound in JavaScript?

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?

like image 738
John Cooper Avatar asked Jun 29 '11 13:06

John Cooper


People also ask

Does JavaScript have array index out of bounds?

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.

How do you resolve an index out of bound exception?

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.

What happens if an array index goes out of bounds?

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.

What is index was outside the bounds of the array?

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.


1 Answers

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*/}
like image 107
Naftali Avatar answered Oct 23 '22 15:10

Naftali