How to check if array element exists or not in javascript?

Pradeep picture Pradeep · Oct 28, 2012 · Viewed 417k times · Source

I am working with Titanium, my code looks like this:

var currentData = new Array();

if(currentData[index]!==""||currentData[index]!==null||currentData[index]!=='null')
{
    Ti.API.info("is exists  " + currentData[index]);
    return true;
}
else
{   
    return false;
}

I am passing an index to the array currentData. I am still not able to detect a non-existing element using above code.

Answer

techfoobar picture techfoobar · Oct 28, 2012

Use typeof arrayName[index] === 'undefined'

i.e.

if(typeof arrayName[index] === 'undefined') {
    // does not exist
}
else {
    // does exist
}