I was going through some JS code and stumbled upon following line which I don't understand:
callback && callback();
What does this line do?
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.
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();
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With