pbaldauf pbaldauf - 1 month ago 4x
jQuery Question

JavaScript convert NULL to 0

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;


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;