How to check if an array index exist?

One line validation. The simplest way.

if(!!currentData[index]){
  // do something
}

Outputs

var testArray = ["a","b","c"]

testArray[5]; //output => undefined
testArray[1]; //output => "b"

!!testArray[5]; //output => false
!!testArray[1]; //output => true

You can also use the findindex method :

var someArray = [];

if( someArray.findIndex(x => x === "index") >= 0) {
    // foud someArray element equals to "index"
}

jsFiddle Demo

Use hasOwnProperty like this:

var a = [];
if( a.hasOwnProperty("index") ){
 /* do something */  
}

As the comments indicated, you're mixing up arrays and objects. An array can be accessed by numerical indices, while an object can be accessed by string keys. Example:

var someObject = {"someKey":"Some value in object"};

if ("someKey" in someObject) {
    //do stuff with someObject["someKey"]
}

var someArray = ["Some entry in array"];

if (someArray.indexOf("Some entry in array") > -1) {
    //do stuff with array
}

Tags:

Javascript