In a jQuery special events article I found syntax that I haven't seen before:
var threshold = data && data.threshold || 1
I have seen before the following:
var threshold = data.threshold || 1
Which to the best of my knowledge means: set to data.threshold or if its value is null then set to 1. Can I please get explanation on first syntax?
&& has higher associativity than ||, so the first example actually means:
var threshold = (data && data.threshold) || 1;
You can read this as "set threshold to data.threshold only if data and data.threshold have truthy values, otherwise set it to 1." If data was null/undefined/etc and the code tried accessing data.threshold without first checking data, this would result in an exception. This syntax allows for checking both at once, in a compact way.
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