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:You can read this as “set
thresholdtodata.thresholdonly ifdataanddata.thresholdhave truthy values, otherwise set it to 1.” Ifdatawas null/undefined/etc and the code tried accessingdata.thresholdwithout first checkingdata, this would result in an exception. This syntax allows for checking both at once, in a compact way.