Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

null checking with "and or" syntax

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?

like image 694
Sergej Popov Avatar asked Nov 16 '25 14:11

Sergej Popov


1 Answers

&& 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.

like image 174
cdhowie Avatar answered Nov 19 '25 07:11

cdhowie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!