I'm using jQuery to get the height of an element. But if the element doesn't exist, the following code will return NULL:
$height = $('#menu li.active ul').height(); // returns integer or null
Is it a cross-browser safe way for getting an integer value under every circumstance with the following code:
$height = $('#menu li.active ul').height() + 0;
Let’s walk through this algorithm with our statement - null > 0. Steps 1 and 2 ask us to call ToPrimitive () on null and 0 respectively to convert these values to their primitive value types (such as Number and String ). The ToPrimitive conversion follows this table.
null gets converted to +0 and 0 remains 0. Neither of the values are NaN so we can skip Steps 6 and 7. It’s at Step 8 that we need to stop. +0 is equal to 0, and the algorithm returns false. Hence, Let’s tackle the next check.
Use the ternary operator to convert NaN to zero, e.g. const result = Number.isNaN (val) ? 0 : val;. If the value is equal to NaN, the operator returns 0, otherwise the value is returned. Copied! The ternary operator is very similar to an if/else statement.
A more efficient solution assumes that the null string is the only anomaly: n=="" || isNaN (n) ? 0 : parseInt (n); (but what if there are other strings?) NaN is the only value in JavaScript which is not equal to itself, so we can use this information in our favour:
There are many ways to deal with this. The one you describe, adding an integer value to coerce the type is fine. You could also convert to a number explicitly:
$height = Number($('#menu li.active ul').height());
// or:
$height = +$('#menu li.active ul').height();
Or you could use a logical operator as null
coerces to false
:
$height = $('#menu li.active ul').height() || 0;
It is safe, yes.
A shorter alternative:
$height = +$('#menu li.active ul').height();
(notice the +
before the $
)
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