Take the 2-minute tour ×

I came across the following line of code in the underscore.js source:

function (obj, iterator, context) {
  iterator || (iterator = _.identity);

Is that syntax equivalent to:

if (!iterator) {
  iterator = _.identity;

Are there any performance benefits to using the former syntax other than reducing the statement to one line?

share|improve this question
wouldn't it be if(!iterator) { ... ? –  lukecampbell May 23 '12 at 19:27
Yes, that's what I meant. –  stinkycheeseman May 23 '12 at 19:29
possible duplicate of Using &&'s short-circuiting as an if statement? –  stinkycheeseman May 23 '12 at 19:49

2 Answers 2

up vote 2 down vote accepted

Yes, it is functionally equivalent to that.

The only benefit to doing it this way is that your check takes up two less lines.

share|improve this answer

This is an effect of boolean short-circuit evaluation. Basically, the evaluation of a boolean expression stops as soon as its outcome is determined:

true || func()

In this case, func() is never called, because whatever it returns, the value of the whole expression will still be true.

false && func()

Similarly, in this case func() is also not called at all, because no matter what it returns, the expression will remain false.

share|improve this answer
Ahh thank you for the proper terminology. It turns out that this question has indeed been asked before. –  stinkycheeseman May 23 '12 at 19:52

Your Answer


