Will this work for testing whether a value at position index exists or not, or is there a better way:
if(arrayName[index]==""){
// do stuff
}
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Conceptually, arrays in JavaScript contain
array.lengthelements, starting witharray[0]up untilarray[array.length - 1]. An array element with indexiis defined to be part of the array ifiis between0andarray.length - 1inclusive. If i is not in this range it’s not in the array.So by concept, arrays are linear, starting with zero and going to a maximum, without any mechanism for having “gaps” inside that range where no entries exist. To find out if a value exists at a given position index (where index is 0 or a positive integer), you literally just use
Now, under the hood, JavaScript engines almost certainly won’t allocate array space linearly and contiguously like this, as it wouldn’t make much sense in a dynamic language and it would be inefficient for certain code. They’re probably hash tables or some hybrid mixture of strategies, and undefined ranges of the array probably aren’t allocated their own memory. Nonetheless, JavaScript the language wants to present arrays of
array.lengthn as having n members and they are named 0 to n – 1, and anything in this range is part of the array.What you probably want, however, is to know if a value in an array is actually something defined – that is, it’s not
undefined. Maybe you even want to know if it’s defined and notnull. It’s possible to add members to an array without ever setting their value: for example, if you add array values by increasing thearray.lengthproperty, any new values will beundefined.To determine if a given value is something meaningful, or has been defined. That is, not
undefined, ornull:or
Interestingly, because of JavaScript’s comparison rules, my last example can be optimised down to this: