0

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.

http://jsfiddle.net/w1tuhtde/

4
  • Why would the collection be undefined, and not an empty array? Commented Aug 29, 2014 at 7:01
  • @elclanrs Because my back end framework doesn't serialize empty arrays. Commented Aug 29, 2014 at 7:02
  • I'd rather have empty array, so 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 do a1 && $.each Commented Aug 29, 2014 at 7:03
  • @elclanrs Yeah, your first suggestion is probably the best intermediate solution. Thanks for your input Commented Aug 29, 2014 at 7:13

1 Answer 1

1

You can of course use the || operator in another way like this:

$.each(a2 || {}, function(k, v){
  console.log(v);
});

or

$.each(a2 || [], function(k, v){
  console.log(v);
});
Sign up to request clarification or add additional context in comments.

4 Comments

Can you please walk me through as to how jQuery evaluates such an assignment a2 || {}?
@Mysteryos if a2 is defined, the whole expression evaluates to a defined object and stops without checking further the {}, then that object is passed in the $.each and it runs normally. Otherwise when a2 is not defined, the whole expression's value depends on the remaining part which is {}, that part is of course defined and it stops returning that empty object. With that empty object passed in $.each, there is in fact no internal loop at all.
Great explanation, thanks :). In terms of performance, will @Johan code: !a1 || $.each(a1, function(k, v){ console.log(v); }); run faster than yours, given that he is doing the empty object check before the call to $.each?
@Mysteryos yes, it is certainly faster but the difference is very very little. This is however shorter and looks better, I think.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.