I was going through some JS code and stumbled upon following line which I don't understand:
callback && callback();
What does this line do?
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.
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.
&&
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();
}
Its checking to see if the callback function is defined. If it is, it is then executing the callback function.