Suppose I have someArray that at runtime will have either 0 or 1 elements.
Would this be a valid use of undefined?
var validItem = someArray[0];
if (validItem !== undefined) {
validItem.doSomething();
}
Suppose I have someArray that at runtime will have either 0 or 1 elements.
Would this be a valid use of undefined?
var validItem = someArray[0];
if (validItem !== undefined) {
validItem.doSomething();
}
this will throw you an exception if elements has no elements and you reference someArray[0]; it will throw you an error you should check like this
if(someArray.length){
someArray[0].doSomething();
}
If your intention is to make sure you don't try to call a function on undefined
, this is what I would do:
var validItem = someArray[0];
if ('doSomething' in validItem && typeof validItem.doSomething === 'function') {
validItem.doSomething();
}