views:

364

answers:

3

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
}
+1  A: 
if(arrayName.length > index && arrayName[index] !== null) {
    //arrayName[index] has a value
}
Rex M
Never compare to null using loose comparison operators (== or !=). This code won't work like you think it is supposed to. It would treat 0, undefined or "" as if they are null.
thomasrutter
@thomas thanks, I typed that out a bit too hastily
Rex M
Also remember that the value might be the "undefined" type, which this modified code snippet treats as "having a value".
thomasrutter
@thomasrutter I'm having trouble coming up with a way it would be possible to end up with an array element that is undefined.
Rex M
Hmmm, does (myarray[1] = undefinedvariable) work? Or just (myarray[1] = undefined)?
thomasrutter
@thomasrutter both of those would throw an exception, no? (undefinedvariable is undefined)
Rex M
You can test it for yourself using something like Firebug. In Javascript, reading the value of an undefined variable does not throw an exception - it returns the undefined value.
thomasrutter
A: 
if(!arrayName[index]){
     // do stuff
}
x2
This would also do stuff if the array value exists but is 0, null, "", etc.
thomasrutter
Thomas is right; however, this is sufficient for many cases (which you should probably enumerate).
Justin Johnson
+4  A: 

All real arrays in Javascript contain array.length elements, starting with array[0] up until array[array.length - 1]. There is no way for an array to have "gaps" in it ie specific indexes that just don't exist, unlike languages like PHP - though it is possible for array values to be null, undefined, NaN, Infinity, 0, or a whole host of different values.

Therefore to find out if a value exists at a given position index (where index is 0 or a positive integer), you literally just use

if (index < array.length) {
  // do stuff
}

I suspect, however, you are not wanting to know if a given value exists, but whether that value is something meaningful. That is, not "undefined", or perhaps, not "undefined or null".

if (typeof array[index] !== 'undefined') {

or

if (typeof array[index] !== 'undefined' && array[index] !== null) {

It depends on what you're trying to achieve.

thomasrutter
Thanks that's got all I need and more.
Ankur
It's highly likely that the OP knows what sort of array s/he's dealing with, but just for completeness: *array-like* objects also typically contain a `length` property, in which case the later two examples are more appropriate.
Justin Johnson
Thanks Justin .... I am actually quite green between the ears about JS, so this is all helpful info
Ankur