JavaScript convert NULL to 0

19,259

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{
    ......
}
Share:
19,259
pbaldauf
Author by

pbaldauf

Updated on June 18, 2022

Comments

  • pbaldauf
    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
    Levent Yumerov over 7 years
    If item with selector '#menu li.active ul' does not exists, using '+' will return NaN.
  • Christoph
    Christoph over 7 years
    No, it returns 0. Tested in Chrome 52
  • VisioN
    VisioN over 7 years
    Logical operator seems to me the most correct solution here.
  • Rory McCrossan
    Rory McCrossan over 7 years
    That's my usual preference too
  • pbaldauf
    pbaldauf over 7 years
    The second version is exactly what I was looking for. Thanks.
  • Levent Yumerov
    Levent Yumerov over 7 years
    For some reason under Kubuntu Chrome 52 returns NaN.
  • Christoph
    Christoph over 7 years
    Sure? I'm using Kubuntu. I used this in the console to test it: +$(".non-existing-class").height()
  • Levent Yumerov
    Levent Yumerov over 7 years
    Edit: I have tested with version 3.1.0.
  • pbaldauf
    pbaldauf over 7 years
    Nice 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.