#javascript
There's an important different between null
and undefined
when it comes to calculation.
For example:
10 - null === 10
10 - undefined === NaN
So, if you set the initial value of some variable to undefined
and later on, use it in a calculation, you need to think about the outcome.
This is also important for jQuery user when you migrate from older version to jQuery 3+.
There's a breaking change that jQuery will return undefined
for methods like width()
, innerWidth()
,... if the caller is empty, for example:
// before 3
$("non-exist").width() === null
$().width() === null
// after 3+
$("non-exist").width() === undefined
$().width() === undefined
If you use these values in calculation, you'll get into trouble:
const innerWidth = $("selector").outerWidth() - 50; // gonna be NaN
To make sure your code always works as expected, use fallback:
const innerWidth = ($("selector").outerWidth() || 0) - 50; // -50
If you think this note resonated, be it positive or negative, please feel free to send me an email and we can talk.