John Cooper
John Cooper

Reputation: 7651

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?

Upvotes: 9

Views: 8592

Answers (6)

Michael Berkowski
Michael Berkowski

Reputation: 270727

if (typeof yourArray[undefinedIndex] === "undefined") {
  // It's undefined
  console.log("Undefined index: " + undefinedIndex;
}

Upvotes: 6

ssapkota
ssapkota

Reputation: 3302

var john = ['asas','gggg','ggg'];
var index=3;
if (john[index] != undefined ){
 console.log(john[index]);
}

Upvotes: 1

Yogurt The Wise
Yogurt The Wise

Reputation: 4499

Javascript has try catch

try
  {
  //your code
  }
catch(err)
  {
  //handle the error - err i think also has an exact message in it.
alert("Error");
  }

Upvotes: 2

Naftali
Naftali

Reputation: 146320

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*/}

Upvotes: 6

CatchingMonkey
CatchingMonkey

Reputation: 1391

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

Upvotes: 1

gen_Eric
gen_Eric

Reputation: 227310

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

Upvotes: 0

Related Questions