15

I was going through some JS code and stumbled upon following line which I don't understand:

callback && callback();

What does this line do?

RuntimeException
  • 1,135
  • 2
  • 11
  • 25
  • 3
    Wow.. I don't think I've seen that many answers that quickly in a long time. – h2ooooooo Oct 01 '13 at 15:37
  • 1
    That usually indicates that a bit of Googling would have done the job. It did. – isherwood Oct 01 '13 at 15:38
  • 1
    sadly SO rep system doesn't reward dupe hunting, which is sometimes a way more useful than answering. – georg Oct 01 '13 at 15:38
  • @thg435 if you see an actual duplicate I'll give you an upvote :) I don't quite agree with isherwood's suggestion. – Halcyon Oct 01 '13 at 15:44
  • @FritsvanCampen: lol, right, I was trusting him blindly. http://stackoverflow.com/questions/5049006/using-s-short-circuiting-as-an-if-statement might fit better. – georg Oct 01 '13 at 15:50
  • I don't think that fits either. It's missing the _optional callback_ connotation, which I think is essential. – Halcyon Oct 01 '13 at 15:52
  • @FritsvanCampen: might be, still both threads do answer the question perfectly. – georg Oct 01 '13 at 15:57

6 Answers6

20

It's a shorthand conditional.

If the left of the && is truth-y, then whatever is on the right side of the && is executed.

This statement says that if callback is defined and truth-y (not null, false, or 0), execute it.

Adam Jenkins
  • 51,445
  • 11
  • 72
  • 100
5

It says, if callback is not falsey, then call callback. So && short circuits if the left side is false, then the right side will be ignored. If the left side is true however, then the right side is evaluated, so it is equivalent to:

if(callback) {
  callback();
}
jbr
  • 6,198
  • 3
  • 30
  • 42
3

First it checks to ensure that callback is defined (more accurately, that it is a truthy value). Then, if it is, it calls that function.

This is useful when defining a function that takes an optional callback. It's a shorthand way of checking if a callback was actually given.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
3

It checks whether callback evalutes to either true or false. This is the same as:

if (callback) {
  callback();
}

If it evaluated to true, the identifier is treated like a function and it is then called.

If it evaluated to false, callback() won't execute.

ComFreek
  • 29,044
  • 18
  • 104
  • 156
1

&& evaluates the left hand side, if it is true it then evaluates the right hand side, if that is true it returns it.

Since there is nothing on the left hand side of the whole expression, this is equivalent to:

if (callback) {
    callback();
}
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

Its checking to see if the callback function is defined. If it is, it is then executing the callback function.

Joshua Allen
  • 367
  • 2
  • 6