I usually check if a collection exists before iterating over it:
var a1 = [1,2,3], a2;
if(a1){
$.each(a1, function(k, v){
console.log(v);
});
}
I thought a bit about an inline solution and came up with this:
!a1 || $.each(a1, function(k, v){
console.log(v);
});
Which seems to work fine. Any downsides or alternatives?
Without the check I would get a Uncaught TypeError: Cannot read property 'length' of undefined exception.
a1 = a1 || []then do the iteration. But first solution is readable and maintainable, second solution is just not worth it. In any case you'd doa1 && $.each