Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does callback && callback() mean in javascript [duplicate]

Tags:

javascript

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

callback && callback();

What does this line do?

like image 791
RuntimeException Avatar asked Oct 01 '13 15:10

RuntimeException


3 Answers

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.

like image 103
Adam Avatar answered Oct 20 '22 10:10

Adam


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();
}
like image 21
jbr Avatar answered Oct 20 '22 11:10

jbr


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.

like image 3
Niet the Dark Absol Avatar answered Oct 20 '22 10:10

Niet the Dark Absol