0

How can I determine if an array has elements and return false if that array is not defined?

I have the array modal.questions

I was using modal.questions.length but now this seems to be a problem if questions is not defined.

Is there a way I can do this using a libray function of _underscore.js or a simple way I can code a function to make the check?

  • @Felix King It is similar but not an exact duplicate The alleged duplicate question considers a zero length array to be valid. The current question does not. Detecting zero length arrays requires more esoteric Javascript like instanceOf – Paul Aug 22 '13 at 11:13
  • @Melina -- Or actualy, your question might be vague. Did you know you can have perfectly good defined array, that is empty, like `A=[];` . Do you want `true` or `false` with that? – Paul Aug 22 '13 at 11:16

5 Answers5

1

if(modal.questions && modal.questions.length > 0) {}

should work.

Tiele Declercq
  • 2,070
  • 2
  • 28
  • 39
0

check if(modal.questions === undefined) first, then do your length check.

Note: in some older browsers it was possible to overwrite value of undefined. In such case a safe check would be if(modal.questions === void 0) as void 0 will return actual undefined value. If however you're targetting modern browsers, you need not worry about that.

Mchl
  • 61,444
  • 9
  • 118
  • 120
  • 1
    If array is null, or for some reason it is not an array, then checking length may throw an error. – Paul Aug 22 '13 at 11:09
0

try like this:

if (typeof array !== 'undefined' && array.length > 0) {
    // existss and have one item
}
Davor Mlinaric
  • 1,989
  • 1
  • 19
  • 26
0
function isEmpty(theArray) {
    return theArray == null || theArray.length <= 0;
}
M. Abbas
  • 6,409
  • 4
  • 33
  • 46
0

This works in all the browsers

if(!Array.isArray) {
  Array.isArray = function (vArg) {
    return Object.prototype.toString.call(vArg) === "[object Array]";
  };
}

//add length check also here
function isEmpty(theArray) {
    return Array.isArray(theArray)    
}

var a = new Array();
var b = null;
var c = undefined;
var d = [];

alert(isEmpty(a)); //true
alert(isEmpty(b)); //false
alert(isEmpty(c)); //false
alert(isEmpty(d)); //true

JSFiddle

Source :)

bhb
  • 2,476
  • 3
  • 17
  • 32