9

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?

Michael Piefel
  • 18,660
  • 9
  • 81
  • 112
John Cooper
  • 7,343
  • 31
  • 80
  • 100

6 Answers6

6
if (typeof yourArray[undefinedIndex] === "undefined") {
  // It's undefined
  console.log("Undefined index: " + undefinedIndex;
}
Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390
  • 2
    His question: **how can i display a message or alert saying that there is no value for the index passed.** – ssapkota Jun 29 '11 at 13:33
  • "Array index out of bounds" and "array has 'undefined' element" should be handled differently. See here: http://stackoverflow.com/questions/6728424/array-out-of-bounds-comparison-with-undefined-or-length-check – Vladislav Rastrusny Aug 22 '16 at 11:32
6
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*/}
Naftali
  • 144,921
  • 39
  • 244
  • 303
  • 2
    dont try to cast the type! use === instead of == ! It'll be faster as well (by nanoseconds, but hey! :) – japrescott Oct 03 '12 at 15:12
  • "Array index out of bounds" and "array has 'undefined' element" should be handled differently. See here: http://stackoverflow.com/questions/6728424/array-out-of-bounds-comparison-with-undefined-or-length-check – Vladislav Rastrusny Aug 22 '16 at 11:31
2

Javascript has try catch

try
  {
  //your code
  }
catch(err)
  {
  //handle the error - err i think also has an exact message in it.
alert("Error");
  }
Yogurt The Wise
  • 4,379
  • 4
  • 34
  • 42
1

Javascript arrays start at 0. so your array contains contents 0 - 'asas', 1 - 'gggg', 2 - 'ggg'.

CatchingMonkey
  • 1,391
  • 2
  • 14
  • 36
1
var john = ['asas','gggg','ggg'];
var index=3;
if (john[index] != undefined ){
 console.log(john[index]);
}
ssapkota
  • 3,262
  • 19
  • 30
0

Arrays are indexed starting with 0, not 1.

There are 3 elements in the array; they are:

john[0] // asas
john[1] // gggg
john[2] // ggg
gen_Eric
  • 223,194
  • 41
  • 299
  • 337