298

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.

2

22 Answers 22

535

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

i.e.

if(typeof arrayName[index] === 'undefined') {
    // does not exist
}
else {
    // does exist
}
7
  • 6
    +1, nice. You can also use if(arrayName[index] === 'undefined') as a shortcut Commented Oct 8, 2013 at 0:08
  • 100
    @AnchovyLegend no, you cannot! But you can use if(arrayName[index] === undefined).
    – Denis V
    Commented Nov 29, 2013 at 15:01
  • 38
    this fails, if the item is there, but it's value is undefined; use this answer instead -> stackoverflow.com/questions/1098040/…
    – Matus
    Commented May 17, 2014 at 21:25
  • as @Matus said, there is more explanation here, you should be aware on. Commented Aug 8, 2014 at 8:47
  • 2
    for if(arrayName[index] === undefined) you may use even shorter one which is if(!arrayName[index]) Commented Jul 17, 2018 at 14:09
90
var myArray = ["Banana", "Orange", "Apple", "Mango"];

if (myArray.indexOf(searchTerm) === -1) {
  console.log("element doesn't exist");
}
else {
  console.log("element found");
}
3
  • 3
    Unfortunately, this one doesn't work in IE 7 and below. Commented Oct 7, 2014 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
    Commented Sep 1, 2016 at 2:49
  • 12
    The OP was looking to see if the given index number exists. This is checking if a given value exists.
    – jonathan.s
    Commented Mar 7, 2019 at 17:53
62

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

return myArr?.[index]
7
  • @dsi you are allways free to check it in console. Anyway it should. Idea is exactly to save you from error on that case.
    – Saulius
    Commented Jul 21, 2021 at 13:07
  • let date = string.match(/Date: (.*)/)?.[1] > SyntaxError: Unexpected token '.' Commented Apr 25, 2022 at 20:19
  • 1
    Wow this is brilliant, tested all the cases and working really well. Commented Feb 28, 2023 at 9:09
  • 1
    What would return if myArr[index] does not exists? Commented Dec 19, 2023 at 13:08
  • 1
    @AdvaitJunnarkar You shouldn't manually set elements of arrays or objects to undefined, if you really want an explicit null value, use null instead, and for object keys use delete, so when you encounter an undefined value, you know that it is truly undefined (the key doesn't exist in the object / array)
    – Fayeure
    Commented Jun 24 at 9:17
35

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!
}

3
  • Only works on numeric index since it searches if the property exists on the object. Examaple let colors = new Array("green", "blue", "yellow"); "yellow" in colors >> false
    – Pol Rué
    Commented Sep 8, 2023 at 9:19
  • 1
    @PolRué That's by design, the in operator checks if the index exists (has an associated value as opposed to being a hole). If you want to check the membership of an element, I suggest using the Set type and its .has method
    – P Varga
    Commented Sep 8, 2023 at 13:39
  • 1
    Yes, I reached that conlusion too. In my case .has worked well
    – Pol Rué
    Commented Sep 15, 2023 at 13:33
23

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

4
  • 4
    This also works for undefined and null values in the array, which none of the other answers here do. Commented Aug 7, 2019 at 15:11
  • 4
    Verified from MDN: "If an Object is an Array, hasOwnProperty method can check whether an index exists." developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
    – Loren
    Commented Nov 27, 2019 at 16:19
  • 2
    Also, hasOwnProperty won't return true for inherited properties like __proto__, this should be the answer.
    – DaCurse
    Commented Apr 28, 2022 at 21:53
  • 2
    This also works for arrays containing zeros and other falsy values +1.
    – Insyte
    Commented Nov 3, 2023 at 19:11
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!")
}

1
  • 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
    Commented Apr 29, 2022 at 22:11
4

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).

1
  • 2
    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
    Commented Oct 11, 2019 at 21:12
4
var demoArray = ['A','B','C','D'];
var ArrayIndexValue = 2;
if(ArrayIndexValue in demoArray){
   //Array index exists
}else{
   //Array Index does not Exists
}
1
  • What are you expecting ..what is the question actually?
    – Geeky
    Commented Oct 31, 2018 at 19:36
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;
    }
});
1
  • 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
    Commented Nov 15, 2019 at 8: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')
3
  • 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
    Commented Dec 16, 2015 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
    Commented Feb 2, 2017 at 0: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. Commented Nov 19, 2020 at 22:39
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
}

2
  • 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
    Commented Dec 21, 2018 at 1: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
    Commented Apr 3, 2019 at 20:08
2

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
3
  • 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
    Commented Aug 19, 2021 at 19:12
  • 3
    testArray = [0, 0, 0] will result in false for every index even though they are given.
    – miile7
    Commented Dec 3, 2021 at 6:50
  • This returns incorrect results if your array contains zero.
    – BurnsBA
    Commented Oct 12, 2022 at 20:50
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.

1
  • 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'); } Commented Nov 26, 2014 at 14:55
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")
1
  • 4
    horribly inefficient. what if I set myArray[1000000] = 'Pear' then your function will take forever. Commented Sep 6, 2018 at 16:52
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');
        }
 }
1

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

1

This is surprisingly simple to check.

const doesIndexExist = (array, index) => {
  return array.length > 0 &&   // array must have at least one value
         index >= 0 &&         // index must be non-negative
         index < array.length  // index must be less than length
}

Why most of the answers (including the chosen one) are incorrect

The chosen answer is incorrect as an array can contain undefined, e.g. const arr = [undefined]. arr[0] exists, but is undefined.

Checking if an index exists vs if it's truthy are two different concerns.

@yeswanth's answer might work if the values being checked are either primitives or if the element being searched is an object and you have a reference to it. It's both inconvenient and too performance intensive for a simple numerical test.

1

"I still can't detect a non-existing index using the above code."

If the goal is purely to validate the existence of an index in an array, then the ideal approach would be to use a function like the following:

function isValidIndex(arr, index) {
    /* 
        Validates given index by checking if it is:
        1. An integer,
        2. Non-negative (0 or positive),
        3. Within the bounds of the given array.
    */
    return Number.isInteger(index) && index >= 0 && index < arr.length;
}

This function accurately evaluates the existence of the given index in the specified arr efficiently and avoids some potential issues that could arise if using some of the other mentioned techniques, such as...

1. Dependency on the Element Value (Using typeof or Optional Chaining):

Whether or not an array has a valid index of the specified value should not depend on the value of the element at that index. Using if (typeof array[index] === 'undefined'), the condition is...

"If the element, if any, of this array at the specified index is undefined...", which is not the same as... "If this array has an element at the specified index...".

It's possible for the array to have an element at that index with an empty slot or undefined value, which would result in a false negative from the check.

JavaScript arrays are technically a predefined object with methods and properties rather than an explicit data type. Array elements are actually stored as object properties with the index as the property name. length is a special Array property that's automatically updated to reflect the highest index + 1. Because of this, an array can be instantiated with a given length, but containing no elements, and the value of the array's length property will reflect the length specified upon instantiation.

For example:

const arr = new Array(5); // arr.length === 5
console.log(arr); // [ <5 empty items> ]

This results in a "sparse array", which contains empty slots, despite having valid indices. Similar to the typeof`` technique, using arr?.[index]has value dependency and will returnundefinedfor an index that ***does*** exist but has an empty slot or anundefined` value.

Additionally, these techniques lack inherent type and range checking for the index itself, which could cause unexpected results if a non-integer or out-of-range value is somehow passed to the function.

2. Value not Index Checking (The includes() Method):

Using the includes() method doesn't validate the existence of an index, but rather the existence of a value within the array.

For example:

const arr = [1, 3, 5];
console.log(arr.includes(3)); // true

The method checks if the value 3 exists within the array, not if the array has index 3. In this case, the method would return true because the array contains the value 3, which would be a false positive for checking if the index 3 exists, as the array only has the indices 0, 1, and 2. In any case, the value could exist at multiple indices, or not at all, and it would still return true or false respectively.

3. Performance Hit Using the in Operator:

The in operator is used to check if a property exists in an object and is a valid way to check if an index exists in an array. However, it isn't the most efficient way to verify an index's existence because:

1) It checks if the property exists in the object OR its prototype chain, which is unecessary for arrays and can also potentially result in false positives if the property is inherited from the object's prototype.

2) It doesn't inherently check the type or range of the index, meaning additional checks would be necessary to ensure the index is a valid integer within the bounds of the array, adding complexity and possibly impacting performance.

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

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

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');
}
1
  • 3
    wrong. what if tmp = [0,0,0,0] then tmp[3] should exist Commented Sep 6, 2018 at 16:50
-2

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
2
  • 1
    what about a[1] = false? 0? ''?
    – AterLux
    Commented Jan 22, 2021 at 13:16
  • This returns incorrect results if your array contains zero.
    – BurnsBA
    Commented Oct 12, 2022 at 20:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.