JavaScript convert NULL to 0
Solution 1
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;
Solution 2
It is safe, yes.
A shorter alternative:
$height = +$('#menu li.active ul').height();
(notice the +
before the $
)
Solution 3
Simplest way to do that..
$height = $('#menu li.active ul').height() || 0;
Here false value will be..
- false
- null
- undefined
- " "
- 0
- NaN
Solution 4
My short solution is:
$height = $('#menu li.active ul').height() || 0
.
If you want more descriptive solution, you can check other users' answers.
Edit: It depends on jQuery version too.
Solution 5
This is a better approach infact...
if($('#menu li.active ul').length > 0){
$height = $('#menu li.active ul').height();
}else{
......
}
pbaldauf
Updated on June 18, 2022Comments
-
pbaldauf almost 2 years
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;
-
Levent Yumerov over 7 yearsIf item with selector '#menu li.active ul' does not exists, using '+' will return NaN.
-
Christoph over 7 yearsNo, it returns
0
. Tested in Chrome 52 -
VisioN over 7 yearsLogical operator seems to me the most correct solution here.
-
Rory McCrossan over 7 yearsThat's my usual preference too
-
pbaldauf over 7 yearsThe second version is exactly what I was looking for. Thanks.
-
Levent Yumerov over 7 yearsFor some reason under Kubuntu Chrome 52 returns NaN.
-
Christoph over 7 yearsSure? I'm using Kubuntu. I used this in the console to test it:
+$(".non-existing-class").height()
-
Levent Yumerov over 7 yearsEdit: I have tested with version 3.1.0.
-
pbaldauf over 7 yearsNice version too. Therefore I will upvote the answer. Not sure if cross-browser compatible and/or dependent on the jQuery version for different result in Kubuntu.