284

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 currentData array. I still can't detect a non-existing index using the above code.

stramin
  • 2,183
  • 3
  • 29
  • 58
Pradeep
  • 6,303
  • 9
  • 36
  • 60

20 Answers20

513

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

i.e.

if(typeof arrayName[index] === 'undefined') {
    // does not exist
}
else {
    // does exist
}
techfoobar
  • 65,616
  • 14
  • 114
  • 135
  • 6
    +1, nice. You can also use `if(arrayName[index] === 'undefined')` as a shortcut – AnchovyLegend Oct 08 '13 at 00:08
  • 95
    @AnchovyLegend no, you cannot! But you can use `if(arrayName[index] === undefined)`. – Denis V Nov 29 '13 at 15:01
  • 35
    this fails, if the item is there, but it's value is undefined; use this answer instead -> http://stackoverflow.com/questions/1098040/checking-if-an-array-key-exists-in-a-javascript-object-or-array – Matus May 17 '14 at 21:25
  • as @Matus said, there is more explanation [here](http://stackoverflow.com/questions/1098040/checking-if-an-array-key-exists-in-a-javascript-object-or-array), you should be aware on. – S.Thiongane Aug 08 '14 at 08:47
  • What if you have a 2D array? (typeof tree[4][4] === 'undefined') If [4][4] does not exist, then you will get an error that it's an undefined object. – Chewie The Chorkie May 18 '18 at 19:41
  • 2
    for if(arrayName[index] === undefined) you may use even shorter one which is if(!arrayName[index]) – Park JongBum Jul 17 '18 at 14:09
  • @ParkJongBum That will only work if they understand "[falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy)" in JavaScript and if the array contains no falsy values. For example, if a[0] exists and is an empty string (or 0 or null or other falsy value), `!a[0]` will return true (saying the element does not exist) instead of false: `a = ['']; if (a[0] === undefined) { console.log('not-exist') } else { console.log('exists') } ; if (!a[0]) { console.log('not-exist') } else { console.log('exists') } ` – jonathan.s Mar 07 '19 at 19:25
92
var myArray = ["Banana", "Orange", "Apple", "Mango"];

if (myArray.indexOf(searchTerm) === -1) {
  console.log("element doesn't exist");
}
else {
  console.log("element found");
}
Pere
  • 1,647
  • 3
  • 27
  • 52
yeswanth
  • 1,543
  • 1
  • 11
  • 19
  • 3
    Unfortunately, this one doesn't work in IE 7 and below. – darksoulsong Oct 07 '14 at 15:21
  • 6
    This in my opinion is the best answer, by now IE 7 is not mainteined any more so it's not a problem. Although I will suggest to use the triple equals `if(myArray.indexOf(searchTerm) === -1)` – Mauro Gava Sep 01 '16 at 02:49
  • 10
    The OP was looking to see if the given **index** number exists. This is checking if a given **value** exists. – jonathan.s Mar 07 '19 at 17:53
46

These days I would take advantage of ecmascript and use it like that

return myArr?.[index]
Saulius
  • 1,736
  • 20
  • 29
29

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!
}
P Varga
  • 19,174
  • 12
  • 70
  • 108
19

Someone please correct me if i'm wrong, but AFAIK the following is true:

  1. Arrays are really just Objects under the hood of JS
  2. Thus, they have the prototype method hasOwnProperty "inherited" from Object
  3. 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

r3wt
  • 4,642
  • 2
  • 33
  • 55
  • 3
    This also works for undefined and null values in the array, which none of the other answers here do. – Jake Thakur Aug 07 '19 at 15:11
  • 3
    Verified from MDN: "If an Object is an Array, hasOwnProperty method can check whether an index exists." https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty – Loren Nov 27 '19 at 16:19
  • Also, `hasOwnProperty` won't return true for inherited properties like `__proto__`, this should be the answer. – DaCurse Apr 28 '22 at 21:53
6

This also works fine, testing by type using === against undefined.

if (array[index] === undefined){ return } // True

Test:

const fruits = ["Banana", "Orange", "Apple", "Mango"];

if (fruits["Cherry"] === undefined){
  console.log("There isn't any cherry in the fruits basket :(")
}

Or similarly:

const fruits = ["Banana", "Orange", "Apple", "Mango"];

if (!fruits["Cherry"]){
  console.log("There isn't any cherry in the fruits basket :(")
}

// No errors: 
if (fruits["Cherry"]){
  console.log("There is some cherry in there!")
}
NVRM
  • 11,480
  • 1
  • 88
  • 87
  • 1
    for cases where undefined is not expected to be a valid element in the array, i will prefer this version, as it is the most efficient way possible. only grab for my answer if undefined is a valid element in your arrays, and you really need to check if anything is existing at that index or not(to avoid useless set of item at that index). this probably wont apply for you if you are not doing embedded development where clock cycles > everything else. – r3wt Apr 29 '22 at 22:11
5

I had to wrap techfoobar's answer in a try..catch block, like so:

try {
  if(typeof arrayName[index] == 'undefined') {
    // does not exist
  }
  else {
  // does exist
  }
} 
catch (error){ /* ignore */ }

...that's how it worked in chrome, anyway (otherwise, the code stopped with an error).

Swiss Mister
  • 3,260
  • 2
  • 20
  • 42
  • 1
    This should only have "broken" with an error if the variable `arrayName` itself (or `index`) did not exist. Simply accessing an undefined array element should not have resulted in an "error"? – MrWhite Oct 11 '19 at 21:12
3

If elements of array are also simple objects or arrays, you can use some function:

// search object
var element = { item:'book', title:'javasrcipt'};

[{ item:'handbook', title:'c++'}, { item:'book', title:'javasrcipt'}].some(function(el){
    if( el.item === element.item && el.title === element.title ){
        return true; 
     } 
});

[['handbook', 'c++'], ['book', 'javasrcipt']].some(function(el){
    if(el[0] == element.item && el[1] == element.title){
        return true;
    }
});
  • `some` is the modernest way around here. It also can even become a one-liner like `myArray.some(el => el.item === element.item && el.title === element.title)` – vahdet Nov 15 '19 at 08:00
3

Consider the array a:

var a ={'name1':1, 'name2':2}

If you want to check if 'name1' exists in a, simply test it with in:

if('name1' in a){
console.log('name1 exists in a')
}else
console.log('name1 is not in a')
Amir
  • 433
  • 4
  • 10
  • 6
    "var a" is not an array object in your case, but a regular object. Should be var a = [ ... ]. I think this is what author needed. – tomazahlin Dec 16 '15 at 13:10
  • 4
    This is how to check for the existence of a key in an object, not the presence of an index in an array. – Ben Hull Feb 02 '17 at 00:58
  • 1
    The `in` operator seems to work with arrays too. Like `2 in [5, 6, 7, 8, 9, 10]` is true, but `6 in [5, 6, 7, 8, 9, 10]` is false. Just change your answer to array to be relevant. – Crouching Kitten Nov 19 '20 at 22:39
3
var demoArray = ['A','B','C','D'];
var ArrayIndexValue = 2;
if(ArrayIndexValue in demoArray){
   //Array index exists
}else{
   //Array Index does not Exists
}
Vikas Kandari
  • 1,612
  • 18
  • 23
2

If you are looking for some thing like this.

Here is the following snippetr

var demoArray = ['A','B','C','D'];
var ArrayIndexValue = 2;
if(demoArray.includes(ArrayIndexValue)){
alert("value exists");
   //Array index exists
}else{
alert("does not exist");
   //Array Index does not Exists
}
Geeky
  • 7,420
  • 2
  • 24
  • 50
  • This is the solution I am going to use im my project today. I have no idea why there were downvotes - this works best for my use case, which is server-side node.js / express. Thank you – mkrufky Dec 21 '18 at 01:53
  • @mkrufky because that is not what this question is for. we've long had the ability prior to `Array.includes` to check if a value is an array, like `demoArray.indexOf(ArrayIndexValue) !== -1`. this question is about checking whether the index exists in the array, which is an entirely different problem – r3wt Apr 03 '19 at 20:08
1

If you use underscore.js then these type of null and undefined check are hidden by the library.

So your code will look like this -

var currentData = new Array();

if (_.isEmpty(currentData)) return false;

Ti.API.info("is exists  " + currentData[index]);

return true;

It looks much more readable now.

vatsal
  • 3,803
  • 2
  • 19
  • 19
  • Even if your answer is right, I would just think twice for this. Your code would become underscore.js dependent only for checking an empty value. Just do a simple wrapper function isset(v) { return (typeof v !== 'undefined'); } – Heroselohim Nov 26 '14 at 14:55
1

This way is easiest one in my opinion.

var nameList = new Array('item1','item2','item3','item4');

// Using for loop to loop through each item to check if item exist.

for (var i = 0; i < nameList.length; i++) {
if (nameList[i] === 'item1') 
{   
   alert('Value exist');
}else{
   alert('Value doesn\'t exist');
}

And Maybe Another way to do it is.

nameList.forEach(function(ItemList)
 {
   if(ItemList.name == 'item1')
        {
          alert('Item Exist');
        }
 }
SBB
  • 8,560
  • 30
  • 108
  • 223
AmJustSam
  • 268
  • 2
  • 9
1

Simple way to check item exist or not

Array.prototype.contains = function(obj) {
    var i = this.length;
    while (i--)
       if (this[i] == obj)
       return true;
    return false;
}

var myArray= ["Banana", "Orange", "Apple", "Mango"];

myArray.contains("Apple")
Suhail Ahmed
  • 350
  • 3
  • 4
1

var fruits = ["Banana", "Orange", "Apple", "Mango"];
if(fruits.indexOf("Banana") == -1){
    console.log('item not exist')
} else {
 console.log('item exist')
}
Mohammed Jafar
  • 493
  • 6
  • 4
1

One line validation. The simplest way.

return !!currentData[index];

Outputs

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

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

!!testArray[5]; //output => false
!!testArray[1]; //output => true
Raphael Soares
  • 482
  • 6
  • 8
  • 1
    It is of course okay, however, when everything become highly nested (harder to read), the way you shown is adding an extra level of complexity for readers. Even for experienced js coders, getting the logic in one read is difficult. – NVRM Aug 19 '21 at 19:12
  • 2
    `testArray = [0, 0, 0]` will result in `false` for every index even though they are given. – miile7 Dec 03 '21 at 06:50
  • This returns incorrect results if your array contains zero. – BurnsBA Oct 12 '22 at 20:50
0

you can simply use this:

var tmp = ['a', 'b'];
index = 3 ;
if( tmp[index]){
    console.log(tmp[index] + '\n');
}else{
    console.log(' does not exist');
}
Salar
  • 5,305
  • 7
  • 50
  • 78
0
(typeof files[1] === undefined)?
            this.props.upload({file: files}):
            this.props.postMultipleUpload({file: files widgetIndex: 0, id})

Check if the second item in the array is undefined using the typeof and checking for undefined

mewc
  • 1,253
  • 1
  • 15
  • 24
0
if(typeof arrayName[index] == undefined) {
    console.log("Doesn't exist")
}
else {
console.log("does exist")
}
-1

When trying to find out if an array index exists in JS, the easiest and shortest way to do it is through double negation.

let a = [];
a[1] = 'foo';
console.log(!!a[0])   // false
console.log(!!a[1])   // true
enchance
  • 29,075
  • 35
  • 87
  • 127