How to check if an array index exists or not in javascript?
Use typeof arrayName[index] === 'undefined'
i.e.
if(typeof arrayName[index] === 'undefined') {
// does not exist
}
else {
// does exist
}
var myArray = ["Banana", "Orange", "Apple", "Mango"];
if (myArray.indexOf(searchTerm) === -1) {
console.log("element doesn't exist");
}
else {
console.log("element found");
}
Someone please correct me if i'm wrong, but AFAIK the following is true:
- Arrays are really just Objects under the hood of JS
- Thus, they have the prototype method
hasOwnProperty
"inherited" fromObject
- in my testing,
hasOwnProperty
can check if anything exists at an array index.
So, as long as the above is true, you can simply:
const arrayHasIndex = (array, index) => Array.isArray(array) && array.hasOwnProperty(index);
usage:
arrayHasIndex([1,2,3,4],4);
outputs: false
arrayHasIndex([1,2,3,4],2);
outputs: true
These days I would take advantage of ecmascript and use it like that
return myArr?.[index]
This is exactly what the in
operator is for. Use it like this:
if (index in currentData)
{
Ti.API.info(index + " exists: " + currentData[index]);
}
The accepted answer is wrong, it will give a false negative if the value at index
is undefined
:
const currentData = ['a', undefined], index = 1;
if (index in currentData) {
console.info('exists');
}
// ...vs...
if (typeof currentData[index] !== 'undefined') {
console.info('exists');
} else {
console.info('does not exist'); // incorrect!
}