Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
like image 912
pbaldauf Avatar asked Sep 02 '16 09:09

pbaldauf


People also ask

How to convert null and 0 to primitive values in JavaScript?

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.

Is NULL NULL a NaN value?

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.

How to convert Nan to zero in JavaScript?

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.

How to parse a null string in JavaScript?

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:


2 Answers

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;
like image 133
Rory McCrossan Avatar answered Sep 19 '22 15:09

Rory McCrossan


It is safe, yes.

A shorter alternative:

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

(notice the + before the $)

like image 42
Christoph Avatar answered Sep 21 '22 15:09

Christoph