JavaScript convert NULL to 0
Asked Answered
W

9

9

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;
Whalebone answered 2/9, 2016 at 9:14 Comment(4)
Why not check if the element exists first? --- Also + 0 will coerce a null to a 0.Cuesta
try with length first if length is > 0 then calculate the heightStressful
It really sounds like bad idea to use a height of 0 for non existing element. See XY problem. And if it was a not so bad idea, jQuery would already do itEpinephrine
RE height of 0 for non-existing element: That surely depends on what you're trying to do. If, say, you're calculating the total height of all elements within a div, counting 0 for the height of a non-existent element is completely correct.Exotoxin
M
20

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;
Mcmahan answered 2/9, 2016 at 9:19 Comment(3)
Logical operator seems to me the most correct solution here.Ciliolate
That's my usual preference tooMcmahan
The second version is exactly what I was looking for. Thanks.Whalebone
F
4

It is safe, yes.

A shorter alternative:

$height = +$('#menu li.active ul').height();

(notice the + before the $)

Fragrant answered 2/9, 2016 at 9:17 Comment(6)
If item with selector '#menu li.active ul' does not exists, using '+' will return NaN.Navicular
No, it returns 0. Tested in Chrome 52Fragrant
For some reason under Kubuntu Chrome 52 returns NaN.Navicular
Sure? I'm using Kubuntu. I used this in the console to test it: +$(".non-existing-class").height()Fragrant
Edit: I have tested with version 3.1.0.Navicular
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.Whalebone
U
3

Simplest way to do that..

$height = $('#menu li.active ul').height() || 0;

Here false value will be..

  • false
  • null
  • undefined
  • " "
  • 0
  • NaN
Undressed answered 2/9, 2016 at 9:28 Comment(0)
S
2

This is a better approach infact...

if($('#menu li.active ul').length > 0){
   $height = $('#menu li.active ul').height();
}else{
    ......
}
Stressful answered 2/9, 2016 at 9:18 Comment(0)
N
2

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.

Navicular answered 2/9, 2016 at 9:20 Comment(0)
R
0

Just check if the element exist:

var $height = 0;
if($('#menu li.active ul').length > 0){
  $height = $('#menu li.active ul').height();
}
Roundhouse answered 2/9, 2016 at 9:18 Comment(0)
O
0

You could check if $("#menu li.active ul") is not null:

$height = $('#menu li.active ul') != null ? $('#menu li.active ul').height() : 0;
Ordzhonikidze answered 2/9, 2016 at 9:19 Comment(0)
S
0

I used the above-accepted answer and other exercises, which give me a nice result.

We can use with parseFloat or parseInt, which give 0 or the actual value. See demo specially last result :

function myFunction() {
  var a = parseFloat("10") + "<br>";
  var b = parseFloat("10.00") + "<br>";
  var c = parseFloat("10.33") + "<br>";
  var d = parseFloat("34 45 66") + "<br>";
  var e = parseFloat("   60   ") + "<br>";
  var f = parseFloat("40 years") + "<br>";
  var g = (parseFloat("1.1234") ||0) + "<br>";

  var n = a + b + c + d + e + f + g;
  document.getElementById("demo").innerHTML = n;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Click the button to parse different strings.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>
Sibelius answered 15/3, 2019 at 9:58 Comment(0)
E
0

Late reply:

I just ran into a similar problem. I have an object that I want to hold counts of, well, no need to get into details of this app, let's just say I get a code and I want to count how many times each code occurs.

My first draft I initialized the object with all possible codes with value zero, like "let counts={F:0,C:0,M:0,N:0}. Then I had a loop with a switch on the code value. That seemed awkward, and required the counting function to know all possible codes.

My second draft I started to write

  if (counts[code]==null) counts[code]=1
  else counts[code]++

I presume that would have worked but it seemed inelegant. So I tried

  counts[code]=+counts[code]+1

Didn't work. If counts[code] wasn't already defined, that returned NaN. It works if counts[code]==null, but not when counts[code] is undefined.

But this works:

  counts[code]=(counts[code] || 0)+1

Not as elegant as I'd like but I generally prefer ugly code that works over pretty code that doesn't work. :-)

Exotoxin answered 10/6 at 6:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.