How to check if array element 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